-
Notifications
You must be signed in to change notification settings - Fork 4
/
Merge Intervals.txt
74 lines (66 loc) · 1.56 KB
/
Merge Intervals.txt
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
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
----------------------------------
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
bool compare(const Interval &a, const Interval &b)
{
if(a.start != b.start)
return a.start < b.start;
else
return a.end < b.end;
}
vector<Interval> merge(vector<Interval> &intervals)
{
vector<Interval> ret;
int n = intervals.size();
if(n == 0)
return ret;
sort(intervals.begin(), intervals.end(), compare);
int i = 0;
while(i < n)
{
ret.push_back(intervals[i++]);
while(i < n && intervals[i].start <= ret.back().end)
ret.back().end = max(ret.back().end, intervals[i++].end);
}
return ret;
}
/////////////////////
///重写与2013-10-2
int compare(const Interval &a, const Interval &b)
{
if(a.start == b.start)
return a.end < b.end;
else
return a.start < b.start;
}
vector<Interval> merge(vector<Interval> &intervals) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<Interval> ret;
if(intervals.size() == 0)
return ret;
sort(intervals.begin(), intervals.end(), compare);
int curmin, curmax;
int i = 0;
while(i < intervals.size())
{
curmin = intervals[i].start;
curmax = intervals[i].end;
while(i < intervals.size() - 1 && intervals[i+1].start <= curmax)
{
curmax = intervals[i + 1].end;
i++;
}
ret.push_back(Interval(curmin, curmax));
i++;
}
return ret;
}