排序:
/** * 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) { vector<Interval> ans; int n = intervals.size(); // 以左边界大小排序 sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){return a.start < b.start;}); for (int i = 0; i < n; ) { int l = intervals[i].start; int r = intervals[i].end; while (i < n-1 && intervals[i+1].start <= r) { // 如果左边界小于前一个右边界 r = max(r, intervals[++i].end); // 更新右边界 } ans.emplace_back(Interval(l, r)); // 记录合并区间 i++; } return ans; } };