-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeIntervals.java
More file actions
68 lines (55 loc) · 1.63 KB
/
Copy pathMergeIntervals.java
File metadata and controls
68 lines (55 loc) · 1.63 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Stack;
public class MergeIntervals {
}
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, Comparator.comparing(interval -> interval[0]));
Stack<int[]> stack = new Stack<>();
stack.push(intervals[0]);
int[] interval1;
int[] interval2;
int a;
int b;
int c;
int d;
for (int i = 1; i < intervals.length; i++) {
interval1 = stack.peek();
interval2 = intervals[i];
a = interval1[0];
b = interval1[1];
c = interval2[0];
d = interval2[1];
// Merge and continue
if (c >= a && c <= b && d > b) {
stack.pop();
stack.push(merge(a, b, c, d, true));
continue;
}
else if (c >= a && c <= b && d <= b) {
stack.pop();
stack.push(merge(a, b, c, d, false));
continue;
}
// or simply add
stack.push(interval2);
}
Iterator<int[]> iterator = stack.iterator();
int[][] answer = new int[stack.size()][2];
for (int i = 0; i < answer.length; i++) {
answer[i] = iterator.next();
}
return answer;
}
private int[] merge(int a, int b, int c, int d, boolean firstCase) {
// first case
if (firstCase) {
return new int[]{a, d};
}
else {
return new int[]{a, b};
}
}
}