首页 > 其他 > 详细

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

时间:2020-07-10 09:43:19      阅读:65      评论:0      收藏:0      [点我收藏+]

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

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

原文:https://www.cnblogs.com/mogeko/p/13277196.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!