LeetcodeMedium- 【56. Merging interval】

Given a set of intervals, please merge all overlapping intervals.

Example 1:

Input: [[1,3], [2,6], [8,10], [15,18]]
Output: [[1,6], [8,10], [15,18]]
Explanation: The interval [1,3] and [2,6] overlap, and merge them into [1,6].
Example 2:

Input: [[1,4], [4,5]]
Output: [[1,5]]
Explanation: The intervals [1,4] and [4,5] can be regarded as overlapping intervals.

Source: LeetCode
link: https://leetcode-cn.com/problems/merge-intervals The
copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

Idea: Sort by the starting point of the search interval to obtain an ordered interval list, and then merge. After sorting, there are only three cases of merge: inclusion, intersection, and separation. It is sufficient to deal with the three situations separately. Each time two adjacent sections are processed, the new section obtained mainly should also be put into the next comparison.

Note: The sort of python list is sorted by timsort by default. The internal realization principle of python sort function

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if intervals == []:
            return []
        # 区间排序
        intervals.sort()
        # print(intervals)
        ans = [intervals[0]] # 加入第一个区间
        i = 1
        while i < len(intervals):
            # 每次比较最后一个加入的区间和当前遍历区间的关系:
            if ans[-1][-1] >= intervals[i][-1]:
                pass
            elif ans[-1][-1] >= intervals[i][0]:
                t = ans.pop()
                ans.append([t[0], intervals[i][-1]])
            else:
                ans.append(intervals[i])
            i += 1
        return ans

 

 
Published 314 original articles · 22 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/qq_39451578/article/details/105263452