Description
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:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
分析
题目的意思是:给你一堆区间,现在再加一个区间,然后把相互覆盖的区间合并。最后输出结果。
- 思想就是找到那些要合并的区间,然后合并之后加入结果集合就行了。
C++代码
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> res;
int n=intervals.size();
int cur=0;
while(cur<n&&intervals[cur].end<newInterval.start){
res.push_back(intervals[cur++]);
}
while(cur<n&&intervals[cur].start<=newInterval.end){
newInterval.start=min(intervals[cur].start,newInterval.start);
newInterval.end=max(intervals[cur].end,newInterval.end);
cur++;
}
res.push_back(newInterval);
for(int i=cur;i<n;i++){
res.push_back(intervals[i]);
}
return res;
}
};
Python 代码
没什么说的,分三种情况分别讨论就行了,注意最后插入的位置要用flag记录一下,不然会有重复插入新区间。
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
left=newInterval[0]
right = newInterval[1]
flag=True
res=[]
for i in range(len(intervals)):
if intervals[i][0]>right:
if flag:
res.append([left,right])
flag=False
res.append(intervals[i])
elif intervals[i][1]<left:
res.append(intervals[i])
else:
left=min(left,intervals[i][0])
right=max(right,intervals[i][1])
if flag:
res.append([left,right])
return res