leetcode_056 Solution

Merge Intervals


合并区间列表

Solution

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
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class {
public List<Interval> merge(List<Interval> intervals) {
List<Interval> res = new ArrayList<Interval>();
if(intervals.size() == 0) {
return res;
}
// 排序
Collections.sort(intervals, new Comparator<Interval>(){
public int compare(Interval i1, Interval i2) {
if(i1.start - i2.start != 0) {
return i1.start - i2.start;
} else {
return i1.end - i2.end;
}
}
});
Interval pre = intervals.get(0);
for(int i = 1; i < intervals.size(); i++){
Interval cur = intervals.get(i);
if(pre.end < cur.start) {
res.add(pre);
pre = cur;
} else {
pre.end = Math.max(pre.end, cur.end);
}
}
res.add(pre);
return res;
}
}

Over!