[Java] 705. Design a hash set---use a fixed-length array instead of a simple HashSet!!!

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 collection.
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.

代码:
private boolean []a=null;
	public MyHashSet() {
    
    
        a=new boolean[1000001];
    }
    
    public void add(int key) {
    
    
       a[key]=true;
    }
    
    public void remove(int key) {
    
    
       a[key]=false;
    }
    public boolean contains(int key) {
    
    
    	return a[key];

    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/114749304