-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_352.java
More file actions
39 lines (32 loc) · 1.13 KB
/
Copy pathP_352.java
File metadata and controls
39 lines (32 loc) · 1.13 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
package leetcode.hard;
import java.util.TreeMap;
@SuppressWarnings({ "unused", "InnerClassMayBeStatic", "PublicConstructorInNonPublicClass" })
public class P_352 {
class SummaryRanges {
TreeMap<Integer, int[]> tm;
public SummaryRanges() {
tm = new TreeMap<>();
}
public void addNum(int val) {
if (tm.containsKey(val)) {
return;
}
final Integer l = tm.lowerKey(val);
final Integer h = tm.higherKey(val);
if (l != null && h != null && tm.get(l)[1] + 1 == val && h == val + 1) {
tm.get(l)[1] = tm.get(h)[1];
tm.remove(h);
} else if (l != null && tm.get(l)[1] + 1 >= val) {
tm.get(l)[1] = Math.max(tm.get(l)[1], val);
} else if (h != null && h == val + 1) {
tm.put(val, new int[] { val, tm.get(h)[1] });
tm.remove(h);
} else {
tm.put(val, new int[] { val, val });
}
}
public int[][] getIntervals() {
return tm.values().toArray(int[][]::new);
}
}
}