1 """
2 Given a collection of intervals, merge all overlapping intervals.
3 Example 1:
4 Input: [[1,3],[2,6],[8,10],[15,18]]
5 Output: [[1,6],[8,10],[15,18]]
6 Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
7 Example 2:
8 Input: [[1,4],[4,5]]
9 Output: [[1,5]]
10 Explanation: Intervals [1,4] and [4,5] are considered overlapping.
11 """
12 """
13 将列表按照第一个值排序。
14 重合情况。
15 拿intervals里要比较的数组右端值和已经存在res中的左端值比较,
16 若前者<=后者,则重叠,更新右端值并存入res。
17 不重合情况。将此intervals存入res即可。
18 """
19 class Solution:
20 def merge(self, intervals):
21 intervals.sort(key=lambda x: x[0]) # !!!把intervals按照第一个值进行排序
22 # print(sorted(C, key=lambda x: x[2]))
23 # x:x[]字母可以随意修改,排序方式按照中括号[]里面的维度进行排序,
24 # [0]按照第一维排序,[2]按照第三维排序
25 #bug 用sorted(intervals) 带0的案例没有通过
26 #Input: [[1,4],[0,4]]
27 #Output: [[1,4]]
28 #Expected: [[0,4]]
29 n = len(intervals)
30 if n == 0:
31 return []
32 res = [intervals[0]]
33 for i in range(1, n):
34 if intervals[i][0] <= res[-1][1]: #重合。
35 # !!!res[-1][1] 第一个-1指的是索引从后往前第一个,用-1表示
36 res[-1][1] = max(res[-1][1], intervals[i][1])
37 else:#不重合
38 res.append(intervals[i])
39 return res