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.
# input:
[[1,3],[2,6],[8,10],[15,18]]
[[1,4],[4,5]]
[[1,4],[2,3]]
[[2,3],[4,5],[6,7],[8,9],[1,10]]
[[3,3],[0,1],[0,0]]
# output:
[[1,6],[8,10],[15,18]]
[[1,5]]
[[1,4]]
[[1,10]]
[[0,1],[3,3]]
先对输入排序,使用C++比较器格式:
vector> merge(vector>& intervals) {
if(intervals.empty())
return {};
vector>res;
//keypoint
sort(begin(intervals), end(intervals),
[](vector a, vector b){return a[0]
Python:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals)==0: return []
intervals=sorted(intervals,key=lambda x : x[0])
res=[intervals[0]]
for n in intervals[1:]:
if n[0] <= res[-1][1]:
res[-1][1]=max(n[1],res[-1][1])
else:
res.append(n)
return res