Design HashSet(Easy)

LeetCode | Design HashSet
题目解析
题目要求不适用自带的哈希类实现一个哈希表的基本操作,添加,删除,查找。

思路
我们用一个数组来作为哈希表,题目的数据最大为1000000,所以我建立了一个大小为1000001的数组,然后添加时对应的数组位置加一,删除时减一,查找是直接找数组对应位置。

代码

class MyHashSet {
    int haxi[1000001]={0}; 
public:
    /** Initialize your data structure here. */
    MyHashSet() {
        
    }
    
    void add(int key) {
        if(haxi[key]==0)
            haxi[key]++;
    }
    
    void remove(int key) {
        if(haxi[key]!=0)
            haxi[key]--;
    }
    
    /** Returns true if this set contains the specified element */
    bool contains(int key) {
        if(haxi[key]!=0){
            return true;
        }
        else
            return false;
    }
};

结果
LeetCode | Design HashSet
小结
首先要了解哈希表的基本知识,该题为比较基础的哈希表题目,主要考哈希表的建立。

相关文章: