-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSparseSet.java
More file actions
110 lines (64 loc) · 2.15 KB
/
Copy pathSparseSet.java
File metadata and controls
110 lines (64 loc) · 2.15 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
106
107
108
109
110
public class SparseSet {
private interface SparseSetDataStructure {
public void add(int item);
public void remove(int item);
public int find(int item);
public void clear();
}
private static class SparseSet1 implements SparseSetDataStructure {
int items, capacity, maxVal;
int[] dense, sparse;
public SparseSet1(int cap, int maxV) {
dense = new int[cap];
sparse = new int[maxV + 1];
capacity = cap;
maxVal = maxV;
items = 0;
}
public void add(int item) {
if(item > maxVal || items >= capacity || find(item) != -1) {
return;
}
dense[items] = item;
sparse[item] = items;
items++;
}
public void remove(int item) {
if(find(item) == -1) {
return;
}
int temp = dense[items - 1];
dense[sparse[item]] = temp;
sparse[temp] = sparse[item];
items--;
}
public int find(int item) {
if(item <= maxVal && sparse[item] < items && dense[sparse[item]] == item) {
return sparse[item];
}
return -1;
}
public void clear() {
items = 0;
}
}
public static void main(String[] args) {
SparseSetDataStructure[] setClasses = new SparseSetDataStructure[]{new SparseSet1(10, 10)};
for (SparseSetDataStructure sparseSet : setClasses) {
sparseSet.add(2);
sparseSet.add(4);
System.out.println(sparseSet.find(4));
System.out.println(sparseSet.find(6));
sparseSet.add(6);
sparseSet.add(8);
System.out.println(sparseSet.find(6));
sparseSet.remove(6);
System.out.println(sparseSet.find(6));
System.out.println(sparseSet.find(8));
sparseSet.clear();
System.out.println(sparseSet.find(2));
System.out.println(sparseSet.find(8));
System.out.println("------");
}
}
}