Title Description
Do not use any hash table built-in library design a hash set
Specifically, your design should include the following functions
add (value): inserts a value to the hash set.
contains (value): Returns the value of the existence of this hash collection.
remove (value): given a hash value is removed from the collection. If the hash value is not set, do nothing.
Example:
= New new MyHashSet hashSet MyHashSet ();
hashSet.add (. 1);
hashSet.add (2);
HashSet.contains (. 1); // Returns to true
HashSet.contains (. 3); // returns false (not found)
hashSet. the Add (2);
HashSet.contains (2); // return to true
hashSet.remove (2);
HashSet.contains (2); // returns false (has been deleted)
note:
All values in the range [0, 1000000] is.
The total number of operations in the range [1, 10000].
Do not use the built-in hash set library.
Code
public class MyHashSet {
private Bucket[] myBuckets;
int totalSize;// HashSet的最大空间
public MyHashSet(){
// 本题哈希算法采用除留余数法;处理冲突的方法使用链地址法
totalSize = 769;// 一般选择质数
myBuckets = new Bucket[totalSize];
// 必须对每一个单元进行实例化,否则将会抛出空指针异常
for(int i=0;i<totalSize;i++){
myBuckets[i] = new Bucket();
}
}
public void add(int key){
int index = key % totalSize;
myBuckets[index].insert(key);
}
public void remove(int key){
int index = key % totalSize;
myBuckets[index].remove(key);
}
public boolean contains(int key){
int index = key % totalSize;
boolean res = myBuckets[index].contains(key);
return res;
}
}
public class Bucket {
// 每个桶维护的其实就是一个链表
// 本可以直接用链表表示桶,但是LinkedList中某些方法无法实现程序功能,所以需要重新封装
List<Integer> container;
public Bucket(){
container = new LinkedList<Integer>();
}
public void insert(int key){
// 按照示例,只有非重复的元素才被添加
if(container.indexOf(key) == -1){
container.add(key);
}
}
public void remove(int key){
int index = container.indexOf(key);
if(index!=-1){
// 存在才能删除
container.remove(index);
}
}
public boolean contains(int key){
if(container.contains(key)){
return true;
}
return false;
}
}