705.设计哈希集合
方法:使用链地址法
设哈希表的大小为base,可以设计一个简单的哈希函数:hash(x) = x mod base
开辟一个大小为base的数组,数组的每个位置是一个链表,当计算出哈希值后,就插入到对应位置的链表
由于使用整数除法作为哈希函数,为了尽可能避免冲突,将base取为一个质数,取base = 769
class MyHashSet {
private static final int BASE = 769;
private LinkedList[] data;
//生成数据结构
public MyHashSet() {
data = new LinkedList[BASE];
for(int i = 0;i<BASE;i++){
data[i] = new LinkedList<Integer>();
}
}
public void add(int key) {
int h = hash(key);
Iterator<Integer> iterator = data[h].iterator();
while(iterator.hasNext()){
Integer element = iterator.next();
if(element == key){
return ;
}
}
data[h].offerLast(key);
}
public void remove(int key) {
int h = hash(key);
Iterator<Integer> iterator = data[h].iterator();
while(iterator.hasNext()){
Integer element = iterator.next();
if(element == key){
data[h].remove(element);
return;
}
}
}
public boolean contains(int key) {
int h = hash(key);
Iterator<Integer> iterator = data[h].iterator();
while(iterator.hasNext()){
Integer element = iterator.next();
if(element == key ){
return true;
}
}
return false;
}
private static int hash(int key){
return key % BASE;
}
}
/**
* 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);
*/