Posted on

Description

Submission

class MyHashMap {
    vector<list<pair<int,int>>> hashMap; 
    const int M = 769;
public:
    /** Initialize your data structure here. */
    MyHashMap() {
        hashMap.resize(M);
    }
    
    /** value will always be non-negative. */
    void put(int key, int value) {
        auto& list = hashMap[key%M];

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

        hashMap[key%M].push_back({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) {
        for(auto [k, v]: hashMap[key%M]) {
            if(k == key) return v;
        }
        return -1;
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        auto& list = hashMap[key%M];
        for(auto it = list.begin(); it != list.end(); ++it) {
            if(it->first == key) {
                list.erase(it);
                break;
            }
            
        }
    }
};

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

Leave a Reply

Your email address will not be published. Required fields are marked *