we must consider every possible condition.
the newInterval at the most front of the array or the middle or the tail of the array.
when the newInterval are among intervals, are they overlap?
these factors all needs to be consider.
/**
* 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) {
vector<Interval> answer;
int flag = 0;
if(intervals.size() == 0)
{
answer.push_back(newInterval);
flag = 1;
}
if(intervals.size() > 0)
if(newInterval.end < intervals[0].start)
{
answer.push_back(newInterval);
flag = 1;
}
for(int i = 0;i< intervals.size();i++)
{
if(intervals[i].end < newInterval.start)
{
answer.push_back(intervals[i]);
continue;
}
if(intervals[i].start > newInterval.end && flag == 0)
{
answer.push_back(newInterval);
flag = 1;
}
if(newInterval.end >= intervals[i].start)
{
if(flag == 1)
answer.pop_back();
if(intervals[i].start < newInterval.start)
newInterval.start = intervals[i].start;
if(intervals[i].end > newInterval.end)
newInterval.end = intervals[i].end;
answer.push_back(newInterval);
flag = 1;
continue;
}
if(intervals[i].start > newInterval.end)
{
answer.push_back(intervals[i]);
}
}
if(flag == 0)
answer.push_back(newInterval);
return answer;
}
};