-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathmergeInterval.java
41 lines (36 loc) · 1.02 KB
/
mergeInterval.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
/**
* 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; }
* }
*/
class Solution {
public List<Interval> merge(List<Interval> intervals) {
List<Interval> result = new ArrayList<>();
if(intervals.size() == 0)
return result;
Collections.sort(intervals, new Comparator<Interval>(){
@Override
public int compare(Interval obj0, Interval obj1)
{
return obj0.start - obj1.start;
}
});
Interval iter = intervals.get(0);
for(Interval cur:intervals)
{
if(cur.start <= iter.end)
iter.end = Math.max(cur.end, iter.end);
else
{
result.add(iter);
iter = cur;
}
}
result.add(iter);
return result;
}
}