-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path56.MergeIntervals.cpp
More file actions
executable file
·74 lines (69 loc) · 2.02 KB
/
56.MergeIntervals.cpp
File metadata and controls
executable file
·74 lines (69 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*************************************************************************
> File Name: 56.MergeIntervals.cpp
> Author: hulkcao
> Mail: [email protected]
> Created Time: 2020年04月07日 星期二 23时50分07秒
************************************************************************/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// https://leetcode.com/problems/merge-intervals/
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
for(auto& arr:intervals) {
if(arr[0]>arr[1]) std::swap(arr[0],arr[1]);
}
std::sort(intervals.begin(),intervals.end(),[](vector<int> a,vector<int> b) {
return a[0]<b[0];
});
vector<vector<int>> result;
for(int i=0; i<intervals.size();)
{
vector<int> tupe = intervals[i];
if(i+1>=intervals.size()) {
result.push_back(tupe);
break;
}
vector<int> next_tupe = intervals[i+1];
while(1)
{
if(tupe[1]<next_tupe[0]) {
result.push_back(tupe);
i++;
break;
}
else {
if(tupe[1]<next_tupe[1]) tupe = vector<int> {tupe[0],next_tupe[1]};
else tupe = vector<int> {tupe[0],tupe[1]};
i++;
if(i+1 >=intervals.size()) {
result.push_back(tupe);
return result;
}
next_tupe = intervals[i+1];
}
}
}
return result;
}
};
void test(vector<vector<int>> arr)
{
Solution s;
auto intervals =s.merge(arr);
for(auto& arr:intervals) {
printf("[%d,%d] ",arr[0],arr[1]);
}
printf("\n");
}
int main()
{
test({{1,3},{4,6},{8,10},{3,9}});
test({{1,3},{2,6},{8,10},{15,18}});
test({{1,4},{4,5}});
test({{1,100}});
test({});
return 0;
}