0%

[筆記] Leetcode - 56. Merge Intervals

https://leetcode.com/problems/merge-intervals/


It means each list in intervals is a range, just to merge the overlapping one, others stay the same.

解題:

  1. sort

sort by the start of each range
save the first one in result
if any the start of each range smaller then the last item in result, it should be merged, otherwise append in result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
# internals.sort(key = lambda x = x[0])
sort_intervals = sorted(intervals, key = lambda x: x[0])

res = [sort_intervals[0]]

for start, end in sort_intervals[1:]:
if res[-1][1] >= start:
res[-1][1] = max(res[-1][1], end)
else:
res.append([start, end])
return res