LeetCode知识点总结 - 705

LeetCode 705. Shortest Completing Word

考点 难度
Hash Table Easy
题目

Design a HashSet without using any built-in hash table libraries.

Implement MyHashSet class:
void add(key) Inserts the value key into the HashSet.
bool contains(key) Returns whether the value key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.

思路

几个assumptions:
1 需要加到HashSet的int的范围是[0, 1000000]
2 操作次数的范围是[0, 10000]
3 不用其他built-in set implementation
步骤:
1 建一个1000001长度的boolean array,默认初始值为false
2 add数字i = 把arraylist的第i位改为true
3 remove数字i = 把arraylist的第i位改为false
4 contains数字i = return arraylist的第i

答案
class MyHashSet {
    
    boolean[] array = new boolean[1000001];

    public MyHashSet() {        
    }
    
    public void add(int key) {
        if (array[key] == false){
            array[key] = true;
        }
    }
    
    public void remove(int key) {
        if(array[key])
        {
            array[key] = false;
            return;
        }
        return;
    }
    
    public boolean contains(int key) {
        return array[key];
    }
}

猜你喜欢

转载自blog.csdn.net/m0_59773145/article/details/121896997