/**
* 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:
struct IntervalKey{
inline bool operator() (const Interval& pLHS, const Interval& pRHS) {
return pLHS.start < pRHS.start;
}
};
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> res;
int size = intervals.size();
if (size == 0) {
res.push_back(newInterval);
return res;
}
intervals.push_back(newInterval);
sort(intervals.begin(), intervals.end(), IntervalKey());
int cnt = 0;
for (int i = 1; i < size + 1; i++) {
if (intervals[i].start <= intervals[cnt].end && intervals[i].end >= intervals[cnt].start) {
intervals[cnt].end = max(intervals[cnt].end, intervals[i].end);
} else {
++cnt;
intervals[cnt].start = intervals[i].start;
intervals[cnt].end = intervals[i].end;
}
}
res.assign(intervals.begin(), intervals.begin() + cnt + 1);
return res;
}
};