#include <vector>
#include <iostream>
using namespace std;
struct Interval
{
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
int BSeachLowerBoundForStart(vector<Interval> &intervals, int start)
{
if(intervals.size() <=0 || start < intervals[0].start ) return -1;
int low = 0;
int high = intervals.size()-1;
int mid = (low + high + 1) / 2;
while(low < high)
{
if(start < intervals[mid].start)
high = mid - 1;
else
low = mid;
mid = (low + high + 1) / 2;
}
return mid;
}
int BSeachUpperBoundForEnd(vector<Interval> &intervals, int end)
{
if(intervals.size() <=0 || intervals[intervals.size()-1].end < end)
return intervals.size();
int low = 0;
int high = intervals.size()-1;
int mid = (low + high) / 2;
while(low < high)
{
if(intervals[mid].end < end)
low = mid + 1;
else
high = mid;
mid = (low + high) / 2;
}
return mid;
}
vector<Interval> InsertInterval(vector<Interval> &intervals, Interval newInterval)
{
int low = BSeachLowerBoundForStart(intervals, newInterval.start);
int high = BSeachUpperBoundForEnd(intervals, newInterval.end);
if (low >=0 && intervals[low].end >= newInterval.start)
newInterval.start = intervals[low].start;
else
low = low + 1;
if(high < intervals.size() && intervals[high].start <= newInterval.end)
newInterval.end = intervals[high].end;
else
high = high - 1;
vector<Interval> r;
int i = -1;
while(++i<low)
r.push_back(intervals[i]);
r.push_back(newInterval);
i = high;
while(++i < intervals.size())
r.push_back(intervals[i]);
return r;
}
using namespace std;
void PrintIntervals(vector<Interval>& v)
{
for (int i = 0; i < v.size(); ++i)
cout << '[' << v[i].start << ',' << v[i].end << "], ";
cout << endl;
}
int main(int argc, char** argv)
{
vector<Interval> v1;
v1.push_back(Interval(1,3));
v1.push_back(Interval(6,9));
vector<Interval> r1 = InsertInterval(v1, Interval(2,5));
PrintIntervals(r1);
vector<Interval> v2;
v2.push_back(Interval(1,2));
v2.push_back(Interval(3,5));
v2.push_back(Interval(6,7));
v2.push_back(Interval(8,10));
v2.push_back(Interval(12,16));
vector<Interval> r2 = InsertInterval(v2, Interval(4,9));
PrintIntervals(r2);
return 0;
}