zoukankan      html  css  js  c++  java
  • Leetcode 705. 设计哈希集合【哈希表模板】

    gate

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

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

    以插入为例,设值为(key)(key)的哈希值为(x)
    检查(x)的链表中,是否存在值为(key)的。
    若不存在,(num[++cnt] = key),连边(head[x] ightarrow 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);
     */
    
  • 相关阅读:
    System.Web.Http.Cors配置跨域访问的两种方式
    asp.net反向代理
    web.config SetAttributes
    remove name="ProxyModule“会导致重复执行
    去空格
    api签名
    C# HttpWebRequest获取COOKIES
    Request.Form接收不到post数据.
    webapi文档工具
    https://gogs.io/
  • 原文地址:https://www.cnblogs.com/mogeko/p/13277196.html
Copyright © 2011-2022 走看看