The leetcode contains several questions related to the merge of number intervals, which are roughly the place where there is an intersection, and these overlapping intervals are merged.
The idea is as follows:
First, sort all intervals according to the beginning, and then start traversing. Compare the size with the end of the currently determined interval and the header of the range to be judged,
1) if the tail is greater than or equal to the head, it indicates that there is an intersection. Then, let's see who has a bigger tail in the two ranges and take a bigger tail;
2) If the tail
Take leetcode56 as an example:
# Definition for an interval. # Class Interval (object): # def _ init _ (self, S = 0, E = 0): # self. start = s # self. end = eclass solution (object): def Merge (self, intervals): "": Type intervals: list [interval]: Rtype: list [interval] "If Len (intervals) = 0: return [] intervals = sorted (intervals, key = Lambda X: X. start) # sort by the first value of each small list incrementally. Res = [intervals [0] For N in intervals [1:]: If n. start <= res [-1]. end: res [-1]. end = max (N. end, Res [-1]. end) # The start of the second is smaller than the tail of the maximum range in res (found with-1) (to prove that the two have an intersection, and then take the greater tail of the two intersections) else: res. append (n) # If the small value of the second interval is greater than the tail of the maximum interval in res (it proves that there is no intersection) return res
[Merge intervals] Some tips