Source of the topic
https://leetcode.com/problems/merge-intervals/
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18] ,
Return [1,6],[8,10],[15,18] .
Test instructions Analysis
INPUT:A List of intervals
Output:a List of intervals but merged
Conditions: If two interval have overlapping, merge
Topic ideas
First, all intervals are sorted according to start, then if the last interval start is in the previous interval, then merge the two interval; if not, add the new interval
AC Code (PYTHON)
1 #Definition for an interval.2 #class Interval (object):3 #def __init__ (self, s=0, e=0):4 #Self.start = s5 #self.end = e6 7 classsolution (object):8 defmerge (self, intervals):9 """Ten : Type Intervals:list[interval] One : Rtype:list[interval] A """ -Intervals.sort (key =LambdaX:x.start) -Length =len (intervals) theres = [] - ifLength = =0: - returnRes - res.append (intervals[0]) + forIinchRange (1, length): -Size =Len (res) + ifRes[size-1].start <= Intervals[i].start <= res[size-1].end: ARes[size-1].end = Max (Intervals[i].end, res[size-1].end) at Else: - res.append (intervals[i]) - - returnRes -
[Leetcode] (python): 056-merge intervals