interval 系列题
一般遇到interval那就排序吧先,毕竟排好序才好对比时间先后是吧
56. Merge Intervals
Difficulty: Hard
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
Hide Company Tags LinkedIn Google Facebook Twitter Microsoft Bloomberg Yelp
思路: 按start time排序!如果下一个interval的start 《=上一个interval的end,说明有交集。有交集就合并,直到没交集了就把新的merge好的append到答案集里。
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
res = []
if not intervals:
return res
inter = sorted(intervals, key=lambda x: x.start)
pre = inter[0]
for i in range(1, len(inter)):
cur = inter[i]
if cur.start <= pre.end:
pre.end = max(pre.end, cur.end)
else:
res.append(pre)
pre = cur
res.append(pre)
return res
57. Insert Interval
Difficulty: Hard
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
Hide Company Tags LinkedIn Google Facebook
思路:遍历list找和new的交集,没交集就直接append到res里,有交集就merge更新new,直到new不能更新了就break,res。appen(new)并把之后剩余的list内容加到res里。其实就是找insert和merge的过程。记得用while!不要用for,用for最后容易出问题!
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
if not intervals:
return [newInterval]
res = []
i = 0
while i < len(intervals):
if newInterval.start <= intervals[i].end:
if newInterval.end < intervals[i].start:
break
newInterval.start = min(intervals[i].start, newInterval.start)
newInterval.end = max(intervals[i].end, newInterval.end)
else:
res.append(intervals[i])
i += 1
res.append(newInterval)
res += intervals[i:]
return res