/
MergeIntervals.java
88 lines (87 loc) · 2.9 KB
/
MergeIntervals.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MergeIntervals {
public static List<Interval> merge(List<Interval> intervals) {
Comparator<Interval> comp = new Comparator<Interval>() {
@Override
public int compare(Interval a, Interval b) {
// TODO Auto-generated method stub
if (a.start == b.start) {
if (a.end < b.end) {
return -1;
} else if (a.end > b.end){
return 1;
} else {
return 0;
}
} else {
if (a.start < b.start) {
return -1;
} else {
return 1;
}
}
}
};
Collections.sort(intervals, comp);
List<Interval> result = new ArrayList<Interval>();
if (intervals.size() == 0)
return result;
int i = 0;
Interval cur = intervals.get(i);
while (i < intervals.size()) {
if (i + 1 < intervals.size()) {
Interval next = intervals.get(i + 1);
if (next.end <= cur.end) {
i++;
continue;
}
if (next.start <= cur.end) {
Interval temp = mergeInterval(cur, next);
cur = temp;
i += 1;
} else {
result.add(cur);
i++;
cur = intervals.get(i);
}
} else {
break;
}
}
result.add(cur);
return result;
}
private static Interval mergeInterval(Interval a, Interval b) {
Interval temp = new Interval();
temp.start = a.start;
temp.end = b.end;
return temp;
}
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> result = new ArrayList<Interval>();
if (intervals.size() == 0) {
result.add(newInterval);
return result;
}
int i = 0;
return result;
}
public static void printIntervals(List<Interval> intervals) {
for (Interval interval: intervals) {
System.out.println(interval.start + " " + interval.end);
}
}
public static void main(String[] args) {
List<Interval> intervals = new ArrayList<Interval>();
int[][] values = {{1,3}, {1, 3}, {2,6}, {8, 10}, {15, 18}};
for (int i = 0; i < values.length; i++) {
Interval temp = new Interval(values[i][0], values[i][1]);
intervals.add(temp);
}
List<Interval> result = merge(intervals);
printIntervals(result);
}
}