[LeetCode] Merge Intervals

56. Merge Intervals

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> res{{intervals[0].front(), intervals[0].back()}};
for(auto& vec : intervals) {
if(vec.front() > res.back().back()) res.push_back(vec);
else res.back()[1] = max(res.back().back(), vec.back());
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/01/PS/LeetCode/merge-intervals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.