Leetcode 816 Solution

This article provides solution to leetcode question 816 (design-hashset)

https://leetcode.com/problems/design-hashset

Solution

class MyHashSet {
    vector<list<int>> hash_set;

public:
    /** Initialize your data structure here. */
    MyHashSet() {
        hash_set.resize(7927);
    }

    void add(int key) {
        int hash_key = key % 7927;

        auto& hash_vals = hash_set[hash_key];

        for (auto val: hash_vals)
            if (val == key)
                return;

        hash_vals.push_back(key);
    }

    void remove(int key) {
        int hash_key = key % 7927;

        auto& hash_vals = hash_set[hash_key];

        for (auto it = hash_vals.begin(); it != hash_vals.end(); it++)
        {
            if (*it == key)
            {
                hash_vals.erase(it);
                return;
            }
        }

    }

    /** Returns true if this set contains the specified element */
    bool contains(int key) {
        int hash_key = key % 7927;

        auto& hash_vals = hash_set[hash_key];

        for (auto val: hash_vals)
            if (val == 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);
 */