Design HashSet
设计一个HashSet
class MyHashSet {
int p = 769;
List<Integer>[] bucket = new LinkedList[p];
/** Initialize your data structure here. */
public MyHashSet() {
for(int i = 0; i < p; i++) {
this.bucket[i] = new LinkedList<Integer>();
}
}
public void add(int key) {
int hash = hash(key);
if(!contains(key))
this.bucket[hash].add(key);
}
public void remove(int key) {
int hash = hash(key);
if(contains(key))
this.bucket[hash].remove(this.bucket[hash].indexOf(key));
}
/** Returns true if this set contains the specified element */
public boolean contains(int key) {
int hash = hash(key);
return this.bucket[hash].indexOf(key) != -1;
}
private int hash(int key) {
return key % p;
}
}
/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet obj = new MyHashSet();
* obj.add(key);
* obj.remove(key);
* boolean param_3 = obj.contains(key);
*/