Skip to content

Instantly share code, notes, and snippets.

@BruceZu
Last active January 21, 2022 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BruceZu/8a390ff73f66f712467d1b2ac7449274 to your computer and use it in GitHub Desktop.
Save BruceZu/8a390ff73f66f712467d1b2ac7449274 to your computer and use it in GitHub Desktop.
QuickSet
class QuickSet {
int[] vi, iv;
int count;
public QuickSet(int N) {
vi = new int[N]; // Value To Index
iv = new int[N]; // index To Value
count = 0;
}
void insert(int x) { // Runtime O(1)
if (!lookup(x)) {
vi[x] = count;
iv[count] = x;
count++;
}
}
void remove(int x) { // Runtime O(1)
if (lookup(x)) {
int c = vi[x];
count--; // swap with the last one
vi[iv[count]] = c;
iv[c] = iv[count];
}
}
boolean lookup(int x) { // Runtime O(1)
return vi[x] < count && iv[vi[x]] == x;
}
void clear() { // Runtime O(1)
count = 0;
}
void iterate(Consumer<Integer> f) { // Runtime O(count)
for (int i = 0; i < count; i++) {
f.accept(iv[i]);
}
}
// test ----------------------------------------------------------------------
public static void main(String[] args) {
QuickSet s = new QuickSet(10);
s.insert(5);
s.insert(6);
s.insert(7);
s.remove(6);
s.insert(9);
s.iterate(v -> System.out.println(v));
s.clear();
s.insert(5);
s.remove(5);
s.insert(9);
s.iterate(v -> System.out.println(v));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment