146.Design HashSet
题目:
Design a HashSet without using any built-in hash table libraries.
在不使用任何内置哈希表库的情况下设计HashSet。
To be specific, your design should include these functions:
具体而言,您的设计应包括以下功能:
add(value)
: Insert a value into the HashSet. 将值插入HashSet。contains(value)
: Return whether the value exists in the HashSet or not.返回值是否存在于HashSet中。remove(value)
: Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.删除HashSet中的值。 如果HashSet中不存在该值,则不执行任何操作。
Example:
MyHashSet hashSet = new MyHashSet(); hashSet.add(1); hashSet.add(2); hashSet.contains(1); // returns true hashSet.contains(3); // returns false (not found) hashSet.add(2); hashSet.contains(2); // returns true hashSet.remove(2); hashSet.contains(2); // returns false (already removed)
Note:
- All values will be in the range of
[0, 1000000]
.所有值都在[0,1000000]范围内。 - The number of operations will be in the range of
[1, 10000]
.操作次数将在[1,10000]范围内。 - Please do not use the built-in HashSet library.请不要使用内置的HashSet库。
解答:
1 class MyHashSet { 2 private int buckets=1000; 3 private int itemsPerBucket=1001; 4 private boolean[][] table; 5 6 /** Initialize your data structure here. */ 7 public MyHashSet() { 8 table=new boolean[buckets][]; 9 } 10 11 public int hash(int key){ 12 return key%buckets; 13 } 14 15 public int pos(int key){ 16 return key/buckets; 17 } 18 19 public void add(int key) { 20 int hashkey=hash(key); 21 if(table[hashkey]==null) 22 table[hashkey]=new boolean[itemsPerBucket]; 23 table[hashkey][pos(key)]=true; 24 } 25 26 public void remove(int key) { 27 int hashkey=hash(key); 28 if(table[hashkey]!=null) 29 table[hashkey][pos(key)]=false; 30 } 31 32 /** Returns true if this set contains the specified element */ 33 public boolean contains(int key) { 34 int hashkey=hash(key); 35 if(table[hashkey]!=null&&table[hashkey][pos(key)]) 36 return true; 37 return false; 38 } 39 } 40 41 /** 42 * Your MyHashSet object will be instantiated and called as such: 43 * MyHashSet obj = new MyHashSet(); 44 * obj.add(key); 45 * obj.remove(key); 46 * boolean param_3 = obj.contains(key); 47 */
详解: