-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path156.merge-intervals.java
More file actions
43 lines (38 loc) · 1.09 KB
/
156.merge-intervals.java
File metadata and controls
43 lines (38 loc) · 1.09 KB
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
/**
* Definition of Interval:
* public class Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
*/
public class Solution {
/*
* @param intervals: interval list.
* @return: A new interval list.
*/
public List<Interval> merge(List<Interval> intervals) {
List<Interval> ans = new ArrayList<>();
if (intervals == null || intervals.size() == 0) {
return ans;
}
Collections.sort(intervals, new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
});
Interval last = intervals.get(0);
for (int i = 1; i < intervals.size(); i++) {
Interval curr = intervals.get(i);
if (last.end >= curr.start) {
last.end = Math.max(last.end, curr.end);
} else {
ans.add(last);
last = curr;
}
}
ans.add(last);
return ans;
}
}