(LC)705. Design a hash set

705. Design Hash Collection

Design a hash set (HashSet) without using any built-in hash table library.

Implement the MyHashSet class:

void add(key) Insert the value key into the hash set.
bool contains(key) Returns whether this value key exists in the hash set.
void remove(key) Remove the given value key from the hash set. If there is no such value in the hash set, nothing is done.

Example:

输入:
[“MyHashSet”, “add”, “add”, “contains”, “contains”, “add”, “contains”, “remove”, “contains”]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
输出:
[null, null, null, true, false, null, true, null, false]

Explanation:
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(1); // return True
myHashSet.contains(3); // return False, (not found)
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(2); // return True
myHashSet.remove(2) ; // set = [1]
myHashSet.contains(2); // return False, (removed)

prompt:

0 <= key <= 106
call add, remove and contains up to 104 times.

class MyHashSet {
    
    

    /** Initialize your data structure here. */
    boolean[] map = new boolean[1000005];
    public MyHashSet() {
    
    

    }
    
    public void add(int key) {
    
    
        map[key]=true;
    }
    
    public void remove(int key) {
    
    
        map[key]=false;
    }
    
    /** Returns true if this set contains the specified element */
    public boolean contains(int key) {
    
    
        return map[key];
    }
}

/**
 * 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);
 */

Guess you like

Origin blog.csdn.net/weixin_45567738/article/details/114761207