/**
* 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:
bool isOverlapped(Interval curInt,int newSta,int newEnd)
{
if(curInt.end<newSta||newEnd<curInt.start)//not overlapped
return false;
else return true;
}
int BinarySearch(vector<Interval> intervals,int newSta)
{
int lefLoc=0;
int rigLoc=intervals.size()-1;
while(lefLoc<=rigLoc)
{
int midLoc=(lefLoc+rigLoc)/2;
if(intervals[midLoc].start<=newSta)
lefLoc=midLoc+1;
else
rigLoc=midLoc-1;
}
return rigLoc;
}
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<Interval> ans;
if(intervals.empty())
{
ans.push_back(newInterval);
return ans;
}
/
int newSta=newInterval.start;
int newEnd=newInterval.end;
int pos=BinarySearch(intervals,newSta);
for(int i=0;i<pos;i++)//do not need merge part one
ans.push_back(intervals[i]);
/
if(pos>=0)
{
if(isOverlapped(intervals[pos],newSta,newEnd))//first merge
{
newSta=min(intervals[pos].start,newSta);
newEnd=max(intervals[pos].end,newEnd);
}
else
ans.push_back(intervals[pos]);
}
/
pos++;
while(pos<=intervals.size()-1)//following merge
{
if(isOverlapped(intervals[pos],newSta,newEnd))
{
newSta=min(intervals[pos].start,newSta);
newEnd=max(intervals[pos].end,newEnd);
pos++;
}
else
break;
}
ans.push_back(Interval(newSta,newEnd));
/
for(int i=pos;i<=intervals.size()-1;i++)//do not need merge part two
{
ans.push_back(intervals[i]);
}
return ans;
}
};
【leetcode】Insert Interval
最新推荐文章于 2020-11-04 20:53:35 发布