Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
void add(key) Inserts the value key into the HashSet.
bool contains(key) Returns whether the value key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
计算哈希值,使用数组实现Hash Set。
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 class MyHashSet { int PRIME = 1009 ; List<Integer>[] data; public MyHashSet () { data = new List [PRIME]; for (int i = 0 ; i < PRIME; i++){ data[i] = new LinkedList <Integer>(); } } public void add (int key) { if (!contains(key)){ int h = getHash(key); data[h].add(key); } } public void remove (int key) { int h = getHash(key); data[h].remove(new Integer (key)); } public boolean contains (int key) { int h = getHash(key); for ( int num : data[h] ){ if ( num == key ){ return true ; } } return false ; } private int getHash (int o) { return o % PRIME; } }