AC
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval)
{
if(intervals.empty())
{
intervals.push_back(newInterval);
return intervals;
}
vector<int> val;
for(int i=0;i < intervals.size();++i)
{
val.push_back(intervals[i].start);
val.push_back(intervals[i].end);
}
int st=0;
int ed=0;
int m=0;
int n=val.size()-1;
int s_flag=0;
int e_flag=0;
while(m < val.size() && n >= 0)
{
if(val[m] >= newInterval.start && s_flag == 0)
{
st=m;//记录端点
s_flag=1;
}
if(val[n] <= newInterval.end && e_flag == 0)
{
ed=n;
e_flag=1;
}
++m;
--n;
}
if(s_flag == 0)
{
intervals.push_back(newInterval);
return intervals;
}
if(s_flag == 1 && e_flag ==1)根据左右端点进行区分
{
if(st%2 == 0 && ed%2 == 0)
{
vector<Interval> tmp;
for(int i=0;i < st/2;++i)
{
tmp.push_back(intervals[i]);
}
Interval nInterval(newInterval.start,val[ed+1]);
tmp.push_back(nInterval);
for(int i=ed/2+1;i < intervals.size();++i)
{
tmp.push_back(intervals[i]);
}
return tmp;
}
if(st%2 == 0 && ed%2 == 1)
{
vector<Interval> tmp;
for(int i=0;i < st/2;++i)
{
tmp.push_back(intervals[i]);
}
Interval nInterval(newInterval.start,newInterval.end);
tmp.push_back(nInterval);
for(int i=(ed+1)/2;i < intervals.size();++i)
{
tmp.push_back(intervals[i]);
}
return tmp;
}
if(st%2 == 1 && ed%2 == 0)
{
vector<Interval> tmp;
for(int i=0;i < (st-1)/2;++i)
{
tmp.push_back(intervals[i]);
}
Interval nInterval(val[st-1],val[ed+1]);
tmp.push_back(nInterval);
for(int i=ed/2+1;i < intervals.size();++i)
{
tmp.push_back(intervals[i]);
}
return tmp;
}
if(st%2 == 1 && ed%2 == 1)
{
vector<Interval> tmp;
for(int i=0;i < (st-1)/2;++i)
{
tmp.push_back(intervals[i]);
}
Interval nInterval(val[st-1],newInterval.end);
tmp.push_back(nInterval);
for(int i=(ed+1)/2;i < intervals.size();++i)
{
tmp.push_back(intervals[i]);
}
return tmp;
}
}
if(e_flag ==0)
{
intervals.insert(intervals.begin(),newInterval);
return intervals;
}
}