Leetcode 817 Solution

This article provides solution to leetcode question 817 (design-hashmap)

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

Solution

class MyHashMap {
    vector<list<pair<int, int>>> hash_map;

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

    /** value will always be non-negative. */
    void put(int key, int value) {
        auto hash_key = key % 7927;

        auto& hash_vals = hash_map[hash_key];

        for (auto it = hash_vals.begin(); it != hash_vals.end(); it++)
        {
            if (it->first == key)
            {
                it->second = value;
                return;
            }
        }

        hash_vals.push_back(make_pair(key, value));
    }

    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    int get(int key) {
        auto hash_key = key % 7927;

        auto& hash_vals = hash_map[hash_key];

        for (auto it = hash_vals.begin(); it != hash_vals.end(); it++)
        {
            if (it->first == key)
                return it->second;
        }

        return -1;
    }

    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        auto hash_key = key % 7927;

        auto& hash_vals = hash_map[hash_key];

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

/**
 * Your MyHashMap object will be instantiated and called as such:
 * MyHashMap obj = new MyHashMap();
 * obj.put(key,value);
 * int param_2 = obj.get(key);
 * obj.remove(key);
 */