forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_56.java
34 lines (27 loc) · 983 Bytes
/
_56.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
package com.fishercoder.solutions;
import com.fishercoder.common.classes.Interval;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class _56 {
public static class Solution1 {
public List<Interval> merge(List<Interval> intervals) {
if (intervals.size() <= 1) {
return intervals;
}
Collections.sort(intervals, (o1, o2) -> o1.start - o2.start);
List<Interval> result = new ArrayList();
for (int i = 0; i < intervals.size(); i++) {
int start = intervals.get(i).start;
int end = intervals.get(i).end;
while (i < intervals.size() && end >= intervals.get(i).start) {
end = Math.max(end, intervals.get(i).end);
i++;
}
result.add(new Interval(start, end));
i--;
}
return result;
}
}
}