LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
[1, 3] [4, 5] => [1, 3] 是不重叠的区间,添加到结果中
[1, 3] [2, 6] => [1, 6]
[1, 7] [2, 6] => [1, 7]
class Solution {
 public:
  vector<vector<int>> merge(vector<vector<int>>& intervals) {
    vector<vector<int>> res;
    if (empty(intervals)) {
      return res;
    }
    sort(begin(intervals), end(intervals),
         [](auto& x, auto& y) { return x[0] < y[0]; });
    for (int i = 0; i < size(intervals) - 1; ++i) {
      if (intervals[i][1] < intervals[i + 1][0]) {
        res.emplace_back(intervals[i]);
      } else {
        intervals[i + 1][0] = intervals[i][0];
        intervals[i + 1][1] = max(intervals[i][1], intervals[i + 1][1]);
      }
    }
    res.emplace_back(intervals.back());
    return res;
  }
};