- Merge Intervals Medium
4236
288
Add to List
Share Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2:
Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
思路:先对输入排序,然后遍历新的序列,如果res为空或者res的最后一个元素和新的元素没有交集,res.append(newValue),否则更新res的最后一个元素的右边界
代码:python3
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda x:x[0])
print(intervals)
res=[]
for interval in intervals:
if not res or interval[0]>res[-1][1] :
res.append(interval)
else:
res[-1][1]=max(interval[1],res[-1][1])
return res
if __name__ == '__main__':
print(Solution().merge([[0,2],[5,10],[13,23],[24,25],[1,5],[8,12],[15,24],[25,26]]))
时间复杂度: 遍历为N,排序为NlogN,总的为O(NlogN) 空间复杂度: O(logN)排序所要空间