Design HashSet
设计一个HashSet
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 |
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); */ |