Merge Intervals Time : Space : 1234567891011121314151617181920212223242526272829303132333435363738/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */vector<Interval> Solution::insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval> res; bool fl = false; int ma = INT_MIN; for(auto& i : intervals) { if(!fl) { if(newInterval.start <= i.start) { if(!res.empty() and res.back().end >= newInterval.start) { res.back().end = max(res.back().end, newInterval.end); } else res.push_back(newInterval); fl = true; } if(!res.empty() and res.back().end >= i.start) { res.back().end = max(res.back().end, i.end); } else res.push_back(i); } else { if(res.back().end >= i.start) { res.back().end = max(res.back().end, i.end); } else res.push_back(i); } if(!fl and res.back().end >= newInterval.start) { res.back().end = max(res.back().end, newInterval.end); fl = true; } } if(!fl) res.push_back(newInterval); return res;}