forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeIntervals.java
37 lines (34 loc) · 1 KB
/
MergeIntervals.java
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
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
/**
* https://leetcode.com/articles/merge-intervals/
*/
public class MergeIntervals {
// 耗时26ms,时间复杂度O(nlgn)
public List<Interval> merge(List<Interval> intervals) {
Interval cur = null;
List<Interval> result = new LinkedList<>();
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
return o1.start - o2.start;
}
});
for (Interval interval : intervals) {
if (cur == null) {
cur = interval;
} else if (interval.start > cur.end) {
result.add(cur);
cur = interval;
} else {
cur.end = Math.max(cur.end, interval.end);
}
}
if (cur != null) {
result.add(cur);
}
return result;
}
}