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]
.
醉了,代码写的太乱,不过还是ac了
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
struct overlap: public binary_function<Interval,Interval,bool>
{
bool operator()(const Interval &x, const Interval &y)const{
if (y.start > x.end || y.end < x.start)
return false;
else
return true;
}
};
struct myless : public binary_function<Interval, Interval, bool>
{
bool operator()(const Interval &x, const Interval &y)const{
if (y.start > x.start)
return false;
else
return true;
}
};
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval> Result;
if (intervals.empty()){
Result.push_back(newInterval);
return Result;
}
//寻找不重合的第一个区间.
vector<Interval>::iterator iter_begin = find_if(intervals.begin(), intervals.end(), bind2nd(overlap(), newInterval));
Result.assign(intervals.begin(), iter_begin);
if (iter_begin==intervals.end())
{
auto it = find_if(Result.begin(),Result.end(), bind2nd(myless(), newInterval));
Result.insert(it, newInterval);
return Result;
}
//确定重合区间的头尾
Interval *merge = new Interval();
if (newInterval.start < (*iter_begin).start)
merge->start = newInterval.start;
else
merge->start = (*iter_begin).start;
int end_tmp = 0;
vector<Interval>::iterator iter = iter_begin;
for (;iter != intervals.end(); ++iter){
if (iter->start>newInterval.end){
merge->end = end_tmp;
break;
}
else
end_tmp = max(newInterval.end, iter->end);
}
if (iter == intervals.end())
merge->end = end_tmp;
Result.push_back(*merge);
//插入余下的区间
Result.insert(Result.end(), iter, intervals.end());
return Result;
}