forked from Viv786ek/Leetcode-Interview-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge Intervals.cpp
More file actions
21 lines (20 loc) · 749 Bytes
/
Merge Intervals.cpp
File metadata and controls
21 lines (20 loc) · 749 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
for (auto interval : intervals) {
// if the list of merged intervals is empty or if the current
// interval does not overlap with the previous, simply append it.
if (merged.empty() || merged.back()[1] < interval[0]) {
merged.push_back(interval);
}
// otherwise, there is overlap, so we merge the current and previous
// intervals.
else {
merged.back()[1] = max(merged.back()[1], interval[1]);
}
}
return merged;
}
};