-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeIntervals.cc
85 lines (65 loc) · 1.71 KB
/
MergeIntervals.cc
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
74
75
76
77
78
79
80
81
82
83
#include <vector>
#include <string>
#include <iostream>
using std::vector;
using std::string;
using std::cout;
using std::endl;
#include <cstdlib>
using std::atoi;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x), next(NULL){}
};
struct Interval{
int start;
int end;
Interval():start(0), end(0) {}
Interval(int s, int e): start(s), end(e){}
};
#include <algorithm>
#include <cstring>
class Solution{
public:
vector<Interval> merge(vector<Interval> &intervals){
vector<Interval> ans;
auto cmp = [](const Interval &lhs, const Interval &rhs){
if(lhs.start == rhs.start){
return lhs.end < rhs.end;
}
return lhs.start < rhs.start;
};
std::sort(intervals.begin(), intervals.end(), cmp);
auto iter = intervals.begin();
if(intervals.end() == iter){
return ans;
}
int start = iter->start, end = iter->end;
for(++iter; iter != intervals.end(); ++iter){
if(iter->start > end){
ans.push_back(std::move(Interval(start, end)));
start = iter->start;
end = iter->end;
}else{
end = std::max(end, iter->end);
}
}
ans.push_back(std::move(Interval(start, end)));
return ans;
}
};
int main(){
Solution slu;
using std::cin;
vector<Interval> inters;
inters.push_back(Interval(1, 3));
inters.push_back(Interval(2, 6));
inters.push_back(Interval(8, 10));
inters.push_back(Interval(15, 18));
auto ans = slu.merge(inters);
for(auto &a: ans){
cout << a.start << " " << a.end << endl;
}
return 0;
}