设计哈希表
原题:
思路: 采用双端链表作为哈希表的基础数据结构,来实现哈希表的增删查询。关键点有两个:
- 一个是哈希函数的确定,这里考虑质数,最大程度地避免哈希冲突。确定好哈希函数之后,后续增删查的函数,便是做完哈希之后再进行。
- 确定一个基础地数据结构。这里选择双向链表。需要注意,在进行增加操作的时候,需要查询增加的元素是否存在,因为哈希表不存储重复值。
上代码:
class MyHashSet {
private Bucket[] bucketArray;
private int keyrange;
/** Initialize your data structure here. */
public MyHashSet() {
this.keyrange=769;
this.bucketArray=new Bucket[this.keyrange];
for(int i=0;i<this.keyrange;i++){
this.bucketArray[i]=new Bucket();
}
}
protected int _hash(int key){
return (key%this.keyrange);
}
public void add(int key) {
int bucketindex=this._hash(key);
this.bucketArray[bucketindex].insert(key);
}
public void remove(int key) {
int bucketindex=this._hash(key);
this.bucketArray[bucketindex].delete(key);
}
/** Returns true if this set contains the specified element */
public boolean contains(int key) {
int bucketindex=this._hash(key);
return this.bucketArray[bucketindex].exist(key);
}
}
class Bucket{
private LinkedList<Integer> con;
public Bucket(){
con=new LinkedList<Integer>();
}
public void insert(Integer key){
int index=this.con.indexOf(key);
if(index==-1){
this.con.addFirst(key);
}
}
public void delete(Integer key){
this.con.remove(key);
}
public boolean exist(Integer key){
int index=this.con.indexOf(key);
return (index!=-1);
}
}