很快解决的一道题。
快速形成思路:
merge 的条件很多,但是不merge其实是只有少数条件,所以从 少数条件 入手。
然后 发现了一个edge case 难处理,就是这种情况
[1, 5], [6, 10], [2, 8]
前面两个不merge,但是第三个可以 "架桥" 把两者连接起来。
为了处理这个情况,就是要先 sort list by the elem_left. 这样就简化了问题!
除此之外,本题技术要点:
1. list.sort(key=lambda x:x[0])
list.sort(key=lambda x:x.age)
list.sort(key=lambda x:x.age, reverse=True)
2. 把 condition 抓准,做抽象,写得简洁。
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# 1. sort by the left side of interval
# 2. iterate from 2nd to last and merge with condition. scan_left > exist_right?
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
# smart1: if merged is empty in the starting state, just append the interval
# smart2: after sorting, the only condition for not merging is the condition mentioned above
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
merged[-1][1] = max(merged[-1][1], interval[1])
return merged
# 过了一周又练习到这一题!!!
# 对我来说 以下 更加 直接的方式
# 每个 iter, 先 在 res 之外确定完了,再决定是否加入 res,只有在 不能merge时 才开始 加入 res
# 如果 可以 merge,那么 就merge。
# 思路很清楚,但是有一些tricky 的地方:1,先加入第一个interval;2,最后还要加一次。
# 相比上面的做法,which is focusing on the last element in the res!! 每次去更新 res[-1],那样的代码还是抽象
# 得更好,还是厉害,只是不容易想到。
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda x: x[0])
base = intervals[0]
left = base[0]
right = base[1]
res = []
for interval in intervals[1:]:
# merge condition
if interval[0] <= right:
# bug: right = interval[1]
right = max(right, interval[1])
# cannot merge, append condition and reset
else:
res.append([left, right])
left = interval[0]
right = interval[1]
res.append([left, right])
return res