import java util AbstractSet import java util Iterator public class In

 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
import java.util.AbstractSet;
import java.util.Iterator;
public class IntSparseSet extends AbstractSet<Integer> {
public int low, high, count;
public int[] sparse, dense;
public IntSparseSet(int LOW, int HIGH) {
low = LOW;
high = HIGH;
sparse = new int[high - low];
dense = new int[high - low];
count = 0;
}
public boolean add(Integer x) {
if(x < high || x >= low) {
if(sparse[x - low] >= count || dense[sparse[x - low]] != x - low) {
dense[count] = x - low;
sparse[x - low] = count;
count++;
return true;
}
}
return false;
}
public void clear() {
count = 0;
}
public boolean contains(Object x) {
int val = (Integer)x;
if(val < low || val >= high) {
return false;
}
return (sparse[val - low] < count && dense[sparse[val - low]] == val - low);
}
public boolean remove(Object x) {
int val = (Integer)x;
if(val >= low && val < high) {
boolean exist = (sparse[val - low] <= (count--) && dense[sparse[val - low]] == (val - low));
if(exist) {
count--;
dense[sparse[val - low]] = dense[count];
sparse[dense[count]] = sparse[val - low];
return true;
}
}
return false;
}
public int size() {
return count;
}
private class MyIterator implements Iterator<Integer> {
public int i = 0;
public Integer next() {
return dense[i++] + low;
}
public boolean hasNext() {
return i < count;
}
public void remove() {
IntSparseSet.this.remove(dense[i - 1] + low);
}
}
public Iterator<Integer> iterator() {
return new MyIterator();
}
}