问题描述:
57. Insert Interval
Hard
1309147Add to ListShare
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]
源码:
解法1:Low比解法(自己想)
按照插入排序的思想,把新加入的vector插进去,然后再按照前一题的思想leetcode【56】Merge Intervals
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> result;
int n = intervals.size();
if(n==0){
result.push_back(newInterval);
return result;
}
int flag = 0;
for(int i=0; i<n-1; i++){
if(newInterval[0]>=intervals[i][0] && newInterval[0]<intervals[i+1][0]){
intervals.insert(intervals.begin()+i+1, newInterval);
flag = 1;
break;
}
}
if(flag == 0){
if(newInterval[0]<=intervals[0][0]){
intervals.insert(intervals.begin(), newInterval);
}
else intervals.push_back(newInterval);
}
// cout<<intervals[0][0]<<endl;
result.push_back(intervals[0]);
for(int i=1; i<n+1; i++){
vector<int> vector_tmp = result.back();
if(intervals[i][0]<=vector_tmp[1]){
// cout<<intervals[i][0]<<vector_tmp[1]<<endl;
int max_tmp = max(vector_tmp[1], intervals[i][1]);
int min_tmp = min(vector_tmp[0], intervals[i][0]);
result.pop_back();
result.push_back(vector<int> {min_tmp, max_tmp});
}
else{
result.push_back(intervals[i]);
}
}
return result;
}
};
解法2:大神解法
用一个变量 cur 来遍历区间,如果当前 cur 区间的结束位置小于要插入的区间的起始位置的话,说明没有重叠,则将 cur 区间加入结果 res 中,然后 cur 自增1。直到有 cur 越界或有重叠 while 循环退出,然后再用一个 while 循环处理所有重叠的区间,每次用取两个区间起始位置的较小值,和结束位置的较大值来更新要插入的区间,然后 cur 自增1。直到 cur 越界或者没有重叠时 while 循环退出。之后将更新好的新区间加入结果 res,然后将 cur 之后的区间再加入结果 res 中即可,参见代码如下:
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> res;
int n = intervals.size(), cur = 0;
while (cur < n && intervals[cur][1] < newInterval[0]) {
res.push_back(intervals[cur++]);
}
while (cur < n && intervals[cur][0] <= newInterval[1]) {
newInterval[0] = min(newInterval[0], intervals[cur][0]);
newInterval[1] = max(newInterval[1], intervals[cur][1]);
++cur;
}
res.push_back(newInterval);
while (cur < n) {
res.push_back(intervals[cur++]);
}
return res;
}
};