-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solution.java
48 lines (44 loc) · 1.36 KB
/
Solution.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
38
39
40
41
42
43
44
45
46
47
48
package _056;
import structure.Interval;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/10/19
* desc :
* </pre>
*/
public class Solution {
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null || intervals.size() <= 1) return intervals;
intervals.sort(new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
if (o1.start < o2.start) return -1;
if (o1.start > o2.start) return 1;
return 0;
}
});
List<Interval> ans = new ArrayList<>();
int start = intervals.get(0).start;
int end = intervals.get(0).end;
for (Interval interval : intervals) {
if (interval.start <= end) {
end = Math.max(end, interval.end);
} else {
ans.add(new Interval(start, end));
start = interval.start;
end = interval.end;
}
}
ans.add(new Interval(start, end));
return ans;
}
public static void main(String[] args) {
Solution solution = new Solution();
Interval.print(solution.merge(Interval.createTestData("[1,3],[2,6],[8,10],[15,18]")));
}
}