57. Insert Interval
难度:Hard
刷题内容
原题连接
- https://leetcode.com/problems/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:
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].
˼· **- ʱ¼ä¸´ÔÓ¶È: O(N)*- ¿Õ¼ä¸´ÔÓ¶È: O(N)***
ÏȼÆËã³öÐÂÇø¼äÔÚÔÏÈÇø¼äÊý×éÖеÄλÖᣱéÀúÊý×飬ÒÀ´Î±È½ÏÁ½¸öÇø¼ä¡£¼Ç¼ l ºÍr¡£·Ö±ð´ú±íÁËÒªÌí¼ÓµÄÇø¼äµÄÆðµãºÍÖյ㡣µÃµ½Î»ÖÃÖ®ºó£¬ÕÒµ½ intervals[i].end < l,Ìí¼Ó½ø·µ»ØÊý×飬½Ó×ÅÔÙÌí¼ÓÇø¼ä[l,r]¡£×îºóÌí¼Ó intervals[i].start > rµÄÇø¼ä¡£
/**
* 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) {
int beg = newInterval.start,en = newInterval.end,l = beg,r = en;
int comp = beg;
for(int i = 0;i < intervals.size();++i)
{
if(comp < intervals[i].start)
{
comp == beg ? l = beg : r = en;
comp = comp == beg ? en : beg;
if(comp == en && en < intervals[i].start)
{
r = en;
break;
}
if(comp == beg)
break;
}
if(comp <= intervals[i].end)
{
comp == beg ? l = intervals[i].start : r = intervals[i].end;
comp = comp == beg ? en : beg;
if(comp == en && en <= intervals[i].end)
{
r = intervals[i].end;
break;
}
if(comp == beg)
break;
}
}
int i = 0;
vector<Interval> ans;
for(;i < intervals.size();++i)
if(intervals[i].end < l)
ans.push_back(intervals[i]);
else
break;
Interval i1(l,r);
ans.push_back(i1);
for(;i < intervals.size();++i)
if(intervals[i].start > r)
break;
for(;i < intervals.size();++i)
ans.push_back(intervals[i]);
return ans;
}
};