题解 | #合并区间#
合并区间
http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
闭区间的右部分,不断和后面的区间右部分比较并合并
class Solution { public: static bool cmp(Interval& a, Interval& b){ return a.start<b.start; } vector<Interval> merge(vector<Interval> &intervals) { //按区间左部分值排序 sort(intervals.begin(), intervals.end(), cmp); vector<Interval> res; int i=0, n = intervals.size(); while(i<n){ int l = intervals[i].start; int r = intervals[i].end; while(i<n-1 && r >= intervals[i+1].start){ r = max(intervals[i+1].end, r); i++; } res.push_back({l, r}); i++; } return res; } };