-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataStreamasDisjointIntervals_352.java
69 lines (65 loc) · 2.46 KB
/
DataStreamasDisjointIntervals_352.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
package org.example;
import java.util.*;
public class DataStreamasDisjointIntervals_352 {
class SummaryRanges {
private HashMap<Integer, Integer> intervalStart;
private HashMap<Integer, Integer> intervalEnd;
private int[] added;
public SummaryRanges() {
intervalStart = new HashMap<>();
intervalEnd= new HashMap<>();
added = new int[10001];
}
public void addNum(int value) {
if (added[value]==1){
return;
}
added[value] = 1;
if (intervalEnd.containsKey(value-1)){
if (intervalStart.containsKey(value+1)){
int end = intervalStart.get(value+1);
int start = intervalEnd.get(value-1);
intervalStart.remove(value+1);
intervalStart.put(start, end);
intervalEnd.remove(value-1);
intervalEnd.put(end, start);
}
else{
int start = intervalEnd.get(value-1);
intervalEnd.remove(value-1);
intervalStart.put(start, value);
intervalEnd.put(value, start);
}
}
else if (intervalStart.containsKey(value+1)){
int end = intervalStart.get(value+1);
intervalStart.remove(value+1);
intervalStart.put(value, end);
intervalEnd.put(end, value);
}
else {
intervalStart.put(value, value);
intervalEnd.put(value, value);
}
}
public int[][] getIntervals() {
ArrayList<int[]> result = new ArrayList<>();
Map.Entry<Integer, Integer> entry;
for (Map.Entry<Integer, Integer> integerIntegerEntry : intervalStart.entrySet()) {
entry = integerIntegerEntry;
result.add(new int[]{entry.getKey(), entry.getValue()});
}
Collections.sort(result, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0]==o2[0]){
return 0;
}
return o1[0]>o2[0] ? 1: -1;
}
});
System.out.println(Arrays.deepToString(result.toArray(new int[0][])));
return result.toArray(new int[0][]);
}
}
}