/
DataStreamAsDisjointIntervals.java
58 lines (45 loc) · 1.27 KB
/
DataStreamAsDisjointIntervals.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
// https://leetcode.com/problems/data-stream-as-disjoint-intervals/
class SummaryRanges {
private final Set<Integer> set;
public SummaryRanges() {
set = new TreeSet<>();
}
public void addNum(int value) {
set.add(value);
}
public int[][] getIntervals() {
int[][] res = new int[set.size()][2];
int start = Integer.MIN_VALUE, last = start, i = 0;
for (int x: set) {
if (start == Integer.MIN_VALUE) {
start = x;
last = x;
continue;
} else {
if (x - last > 1) {
res[i][0] = start;
res[i][1] = last;
start = x;
last = x;
i++;
} else {
last = x;
}
}
}
res[i][0] = start;
res[i][1] = last;
i++;
int[][] result = new int[i][2];
for (int j = 0; j < result.length; j++) {
result[j] = res[j];
}
return result;
}
}
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(value);
* int[][] param_2 = obj.getIntervals();
*/