[LeetCode] 56. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { if (intervals.empty()) return {};
// 先对区间进行排序,以 start 的值从小到大来排序 sort(intervals.begin(), intervals.end()); vector<vector<int>> res{intervals[0]};
// 首先把第一个区间存入结果中,然后从第二个开始遍历区间集,如果结果中最后一个区间和遍历的当前区间无重叠,直接将当前区间存入结果中,
// 如果有重叠,将结果中最后一个区间的 end 值更新为结果中最后一个区间的 end 和当前 end 值之中的较大值 for (int i = 1; i < intervals.size(); ++i) { if (res.back()[1] >= intervals[i][0]) { res.back()[1] = max(res.back()[1], intervals[i][1]); } else { res.push_back(intervals[i]); } } return res; } };
class Solution { public: static bool compareAsc(const vector<int> &value1, const vector<int> &value2) { return value1[0] < value2[0]; } vector<vector<int>> merge(vector<vector<int>>& intervals) { if (intervals.empty()) return {}; sort(intervals.begin(), intervals.end(), compareAsc); vector<vector<int>> res{intervals[0]}; for (int i = 1; i < intervals.size(); ++i) { if (res.back()[1] >= intervals[i][0]) { res.back()[1] = max(res.back()[1], intervals[i][1]); } else { res.push_back(intervals[i]); } } return res; } };
上边两个都是等效的。
sort 函数的坑: