-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSparseSet.java
More file actions
105 lines (82 loc) · 2.27 KB
/
SparseSet.java
File metadata and controls
105 lines (82 loc) · 2.27 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package gfg.ds.advanced;
import java.util.HashSet;
import java.util.Set;
/** @noinspection WeakerAccess */
public class SparseSet {
private int[] dense;
private int[] sparse;
private int capacity;
private int maxPossibleValue;
private int size;
public SparseSet(int capacity, int maxPossibleValue) {
this.capacity = capacity;
this.dense = new int[capacity];
this.maxPossibleValue = maxPossibleValue;
this.sparse = new int[maxPossibleValue + 1];
}
public boolean canBeInserted(int data) {
return data <= maxPossibleValue && size < capacity;
}
/** t=O(1) */
public SparseSet add(int data) {
assert canBeInserted(data) : "Can't insert";
if (search(data)) {
return this;
}
dense[size] = data;
sparse[data] = size;
size++;
return this;
}
/** t=O(1) */
public boolean search(int data) {
return data <= maxPossibleValue && sparse[data] < size && dense[sparse[data]] == data;
}
/** t=O(1) */
public SparseSet delete(int data) {
assert search(data) : "Not found";
int index = sparse[data];
dense[index] = dense[size - 1];
sparse[dense[size - 1]] = index;
size--;
return this;
}
/** t=O(1) */
public void clear() {
size = 0;
}
/** t=O(n) */
public Set<Integer> values() {
Set<Integer> values = new HashSet<>();
for (int i = 0; i < size; i++) {
values.add(dense[i]);
}
return values;
}
/** t=O(max(n1, n2)) */
public SparseSet union(SparseSet other) {
SparseSet union =
new SparseSet(size + other.size, Math.max(maxPossibleValue, other.maxPossibleValue));
for (int i = 0; i < size; i++) {
union.add(dense[i]);
}
for (int i = 0; i < other.size; i++) {
union.add(other.dense[i]);
}
return union;
}
/** t=O(min(n1, n2)) */
public SparseSet intersection(SparseSet other) {
SparseSet intersection =
new SparseSet(
Math.min(size, other.size), Math.max(maxPossibleValue, other.maxPossibleValue));
SparseSet small = size < other.size ? this : other;
SparseSet large = size < other.size ? other : this;
for (int i = 0; i < small.size; i++) {
if (large.search(small.dense[i])) {
intersection.add(small.dense[i]);
}
}
return intersection;
}
}