LeetCode 57. 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]
.
按照上一题的方法,时间复杂度O(N*log(N))
- 将给定区间
push_back
到整体区间; - 然后排序,然后按照上一题的方法过一遍就可以了。
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
bool cmp(const Interval &a, const Interval &b)
{
return a.start < b.start;
}
class Solution {
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
intervals.push_back(newInterval);
sort(intervals.begin(),intervals.end(), cmp);
vector<Interval> ans;
int b = intervals[0].start, e = intervals[0].end;
for(int i=1; i<intervals.size(); ++ i)
{
if(intervals[i].start > e)
{
ans.push_back(Interval(b, e));
b = intervals[i].start, e = intervals[i].end;
}
else
{
if(intervals[i].end > e)
e = intervals[i].end;
}
}
ans.push_back(Interval(b, e));
return ans;
}
};
利用数组有序,时间复杂度O(n)
- 每次比较给定区间的起始位置和当前期间的起始位置
- 根据起始位置的大小,选取起始位置小的区间
- 判断两个区间是否有交叉。有的话,当前区间往后挪动,直到没有交叉。然后
break
掉 - 将剩下的区间加入答案中。
/**
* 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) {
if(intervals.size() == 0)
return vector<Interval>{newInterval, };
vector<Interval> ans;
int b, e, i;
bool used = false;
for(i=0; i<intervals.size(); ++ i)
{
if(intervals[i].start <= newInterval.start)
{
b = intervals[i].start, e = intervals[i].end;
if(newInterval.start <= e)
{
used = true;
e = max(e, newInterval.end);
while(i+1 < intervals.size() && intervals[i+1].start <= e)
i ++;
e = max(e, intervals[i].end);
i ++;
}
}
else
{
used = true;
b = newInterval.start, e = newInterval.end;
if(newInterval.end >= intervals[i].start)
{
e = max(e, intervals[i].end);
while(i+1 < intervals.size() && intervals[i+1].start <= e)
i ++;
e = max(e, intervals[i].end);
i ++;
}
}
ans.push_back(Interval(b, e));
if(used)
break;
}
if(used == false)
ans.push_back(newInterval);
else
for(; i<intervals.size(); ++ i)
ans.push_back(intervals[i]);
return ans;
}
};