/* 返回顶部 */

Leetcode 705. 设计哈希集合【哈希表模板】

gate

第一次在\(Leetcode\)做题...

对于每个哈希值建一个链表(链式前向星)

以插入为例,设值为\(key\)\(key\)的哈希值为\(x\)
检查\(x\)的链表中,是否存在值为\(key\)的。
若不存在,\(num[++cnt] = key\),连边\(head[x]\rightarrow cnt\)

如果是哈希映射\((map)\),把int num[]改为pair num<int,int>大概即可。

执行用时:172 ms, 在所有 C++ 提交中击败了95.64% 的用户
内存消耗:35.7 MB, 在所有 C++ 提交中击败了100.00% 的用户

const int maxn = 10005;
const int mod = 999979;
int cnt,head[mod],nxt[maxn],num[maxn];
int top,stk[maxn];

class MyHashSet {
public:
    /** Initialize your data structure here. */
    MyHashSet() {
        while(cnt) nxt[cnt--] = 0;
        while(top) head[stk[top--]] = 0;
    }
    
    void add(int key) {
        int x = key % mod;
        for(int i = head[x];i;i = nxt[i])
            if(num[i] == key)
                return;
        if(!head[key]) stk[++top] = x;
        num[++cnt] = key;
        nxt[cnt] = head[x];
        head[x] = cnt;
    }
    
    void remove(int key) {
        int x = key % mod;
        for(int i = head[x];i;i = nxt[i])
            if(num[i] == key){
                num[i] = -1;
                return;
            }
    }
    
    /** Returns true if this set contains the specified element */
    bool contains(int key) {
        int x = key % mod;
        for(int i = head[x];i;i = nxt[i])
            if(num[i] == key)
                return true;
        return false;
    }
};

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet* obj = new MyHashSet();
 * obj->add(key);
 * obj->remove(key);
 * bool param_3 = obj->contains(key);
 */
posted @ 2020-07-10 01:06  Mogeko  阅读(145)  评论(0编辑  收藏  举报