To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.
Pseudo Code:-
Takeaways and follow ups:-
Code:
class MyHashSet {
int numbuckets;
List[] buckets;
private int hash_function(int key){
return key%numbuckets;
} /** Initialize your data structure here. */
public MyHashSet() {
numbuckets=15000;
buckets=new LinkedList[numbuckets];
} public void add(int key) {
int i=hash_function(key);
if(buckets[i]==null) buckets[i]=new LinkedList<>();
if(buckets[i].indexOf(key)==-1)
buckets[i].add(key);
}public void remove(int key) {
int i=hash_function(key);
if(buckets[i]==null) return;
if(buckets[i].indexOf(key)!=-1)
buckets[i].remove(buckets[i].indexOf(key));
} /** Returns true if this set contains the specified element */
public boolean contains(int key) {
int i=hash_function(key);
if(buckets[i]==null || buckets[i].indexOf(key)==-1) return false;
return true;
}
}