题目描述
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
(sort) $O(nlogn)$
存入新的interval,sort数组然后进行合并
时间复杂度
sort花费O(nlogn)
O(n)
参考文献
C++ 代码
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
intervals.push_back(newInterval);
sort(intervals.begin(), intervals.end());
vector<vector<int>> res;
res.push_back(intervals[0]); //先压入一个interval
for(int i=1;i<intervals.size();i++)
{
vector<int> out=res.back();
if(intervals[i][0]<=out[1])
{
int end=max(out[1],intervals[i][1]);
res.pop_back();
res.push_back({out[0], end});
}
else
{
res.push_back(intervals[i]) ;
}
}
return res;
}
};
算法2
(遍历) $O(n)$
遍历数组,比较新的interval是否应该插入,然后合并
时间复杂度
遍历一遍,O(n)
O(n)
参考文献
C++ 代码
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
if(intervals.size()==0) return {newInterval};
vector<vector<int>> res;
bool st=false;
int n=intervals.size(), insertstart=newInterval[0], insertend=newInterval[1];
if(insertstart<intervals[0][0])
{
res.push_back(newInterval);
st=true;
}
else
res.push_back(intervals[0]); //先压入一个interval
for(int i=0;i<intervals.size();i++)
{
if(!st)
{
if(insertstart<intervals[i][0])
{
res.push_back(newInterval);
st=true;
}
}
vector<int> out=res.back();
if(intervals[i][0]<=out[1] )
{
int end=max(out[1],intervals[i][1]);
res.pop_back();
res.push_back({out[0], end});
}
else
{
res.push_back(intervals[i]) ;
}
out=res.back();
if(!st)
{
if(newInterval[0]<=out[1])
{
int end=max(out[1],newInterval[1]);
res.pop_back();
res.push_back({out[0], end});
st=true;
}
else if(newInterval[0]>out[1] && (newInterval[0]<=intervals[i][0] ))
{
res.push_back(newInterval);
st=true;
}
}
}
if(!st)
res.push_back(newInterval);
return res;
}
};