插入区间--Insert Intervals
https://leetcode.com/problems/insert-interval/
Insert Interval
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]
.
题意:插入区间,并简化合并
将需要插入的区间和原区间列合在一起,然后利用 Merge Intervals的方法进行合并简化。
1 # Definition for an interval.
2 # class Interval:
3 # def __init__(self, s=0, e=0):
4 # self.start = s
5 # self.end = e
6
7 class Solution:
8 # @param {Interval[]} intervals
9 # @param {Interval} newInterval
10 # @return {Interval[]}
11 def insert(self, intervals, newInterval):
12 intervals.append(newInterval)
13 intervals.sort(key=lambda x:x.start)
14 res=[]
15 length=len(intervals)
16 for i in range(length):
17 if res==[]:
18 res.append(intervals[i])
19 else:
20 size=len(res)
21 if res[size-1].start<=intervals[i].start<=res[size-1].end:
22 res[size-1].end=max(intervals[i].end,res[size-1].end)
23 else:
24 res.append(intervals[i])
25 return res