feat: 56_merge_intervals
This commit is contained in:
parent
e960461b06
commit
8f699a9669
33
56_merge_intervals/main.cpp
Normal file
33
56_merge_intervals/main.cpp
Normal file
@ -0,0 +1,33 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
vector<vector<int>> merge(vector<vector<int>>& intervals) {
|
||||
sort(intervals.begin(), intervals.end(), [](vector<int> a, vector<int> b) {
|
||||
if (b[0] > a[0]) return true;
|
||||
if (b[0] < a[0]) return false;
|
||||
return b[1] > a[1];
|
||||
});
|
||||
|
||||
vector<vector<int>> result;
|
||||
|
||||
for (int i = 0; i < intervals.size(); i++) {
|
||||
int currentStart = intervals[i][0], currentEnd = intervals[i][1];
|
||||
|
||||
int j = i + 1;
|
||||
while (j < intervals.size() &&
|
||||
currentStart <= intervals[j][0] &&
|
||||
intervals[j][0] <= currentEnd) {
|
||||
currentEnd = max(currentEnd, intervals[j][1]);
|
||||
j++;
|
||||
}
|
||||
i = j - 1;
|
||||
|
||||
vector<int> toPush{currentStart, currentEnd};
|
||||
result.emplace_back(toPush);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user