Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
思路:
首先,将 intervals排序,然后随时比较前一个的end与后一个的start的关系,及时更新返回值。
vector<Interval> merge(vector<Interval>& intervals) { int n = intervals.size(); vector<Interval> ret; if (n <= 1)return intervals; sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){return a.start < b.start;}); ret.push_back(intervals[0]); for (int i = 1; i < n; i++) { if (ret.back().end < intervals[i].start)ret.push_back(intervals[i]); else ret.back().end = max(ret.back().end , intervals[i].end); } return ret; }
参考:
https://discuss.leetcode.com/topic/20263/c-10-line-solution-easing-understanding