题解 | #合并区间#
合并区间
http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
/** * 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> merge(vector<Interval> &intervals) { // 思路: // (1) 将intervals首个元素放到ans中 // (2) 遍历intervals的剩余元素elem,如果ans.back()大于elem.start范围内,更新back的值 // (3) 如果不在,那么就将其保存到ans中 if(intervals.empty()){ return {}; } sort(intervals.begin(), intervals.end(), [&](Interval& a, Interval& b){ return a.start == b.start ? a.end < b.end : a.start < b.start; }); vector<Interval> ans; int size = intervals.size(); ans.push_back(intervals[0]); for(int i = 1; i < size; ++i){ int end = ans.back().end; Interval elem= intervals[i]; if( end >= elem.start){ ans.back().end = max(end, elem.end); }else{ ans.push_back(elem); } } return ans; } };