LeetCode *705. 设计哈希集合

2022-01-13 14:42:38 浏览数 (1)

题目

思路

用链表模拟,可以取769(看的官方)为最大,也可以直接开个大数组也能过

代码语言:javascript复制
class MyHashSet {
public:
    vector<list<int>> mp;
    const int base = 769;
    int hash(int n) {
        return n % base;
    }

    /** Initialize your mp structure here. */
    MyHashSet() {
        mp = vector<list<int>>(base);
    }

    void add(int key) {
        int m = hash(key);
        for (auto it = mp[m].begin(); it != mp[m].end(); it  ) {
            if ((*it) == key) return;
        }
        mp[m].push_back(key);
    }
    
    void remove(int key) {
        int m = hash(key);
        for (auto it = mp[m].begin(); it != mp[m].end(); it  ) {
            if ((*it) == key) {
                mp[m].erase(it);
                return;
            }
        }
    }
    
    /** Returns true if this set contains the specified element */
    bool contains(int key) {
        int m = hash(key);
        for (auto it = mp[m].begin(); it != mp[m].end(); it  ) {
            if ((*it) == 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);
 */

0 人点赞