/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<Interval> pre; vector<Interval> post; int low = newInterval.start; int high = newInterval.end; for(int i = 0; i < intervals.size(); i++){ if(intervals[i].end < low){ pre.push_back(intervals[i]); } if(intervals[i].start > high){ post.push_back(intervals[i]); } } int p; if(intervals.empty() || pre.size() == intervals.size()){ p = low; }else{ p = min(low, intervals[pre.size()].start); } int q; if(intervals.empty() || post.size() == intervals.size()){ q = high; }else{ q = max(high, intervals[intervals.size()-1-post.size()].end); } pre.push_back(Interval(p,q)); pre.insert(pre.end(), post.begin(), post.end()); return pre; } };