-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntervalProblem.java
More file actions
50 lines (44 loc) · 1.61 KB
/
Copy pathIntervalProblem.java
File metadata and controls
50 lines (44 loc) · 1.61 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
44
45
46
47
48
49
50
/*
* Given a collection of intervals, merge all overlapping intervals.
*
For example:
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
Make sure the returned intervals are sorted.
*/
import java.util.*;
public class IntervalProblem{
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
if(intervals == null || intervals.size() <= 1)
return intervals;
Collections.sort(intervals, new IntervalComparator());
ArrayList<Interval> result = new ArrayList<Interval>();
Stack<Interval> s = new Stack<Interval>();
Interval prev = intervals.get(0);
for(int i = 1; i < intervals.size(); i++){
Interval current = intervals.get(i);
if(prev.end >= current.start){
Interval merged = new Interval(prev.start, Math.max(prev.end, current.end));
prev = merged;
}
else{
result.add(prev);
prev = current;
}
}
result.add(prev);
return result;
}
public static void main(String[] args){
IntervalProblem ip = new IntervalProblem();
ArrayList<Interval> intervals = new ArrayList<Interval>();
intervals.add(new Interval(1, 3));
intervals.add(new Interval(2, 6));
intervals.add(new Interval(8, 10));
intervals.add(new Interval(15, 18));
ArrayList<Interval> result = ip.merge(intervals);
for(int i =0; i < result.size(); i++){
System.out.printf("[%d, %d] ", result.get(i).start, result.get(i).end);
}
}
}