classMyHashMap { private: vector<list<pair<int, int>>> data; staticconstint base = 769; staticinthash(int key){ return key % base; } public: /** Initialize your data structure here. */ MyHashMap(): data(base) {} /** value will always be non-negative. */ voidput(int key, int value){ int h = hash(key); for (auto it = data[h].begin(); it != data[h].end(); it++) { if ((*it).first == key) { (*it).second = value; return; } } data[h].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 */ intget(int key){ int h = hash(key); for (auto it = data[h].begin(); it != data[h].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 */ voidremove(int key){ int h = hash(key); for (auto it = data[h].begin(); it != data[h].end(); it++) { if ((*it).first == key) { data[h].erase(it); return; } } } };
/** Initialize your data structure here. */ publicMyHashMap() { data = newLinkedList[BASE]; for (inti=0; i < BASE; ++i) { data[i] = newLinkedList<Pair>(); } } /** value will always be non-negative. */ publicvoidput(int key, int value) { inth= hash(key); Iterator<Pair> iterator = data[h].iterator(); while (iterator.hasNext()) { Pairpair= iterator.next(); if (pair.getKey() == key) { pair.setValue(value); return; } } data[h].offerLast(newPair(key, value)); } /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ publicintget(int key) { inth= hash(key); Iterator<Pair> iterator = data[h].iterator(); while (iterator.hasNext()) { Pairpair= iterator.next(); if (pair.getKey() == key) { return pair.value; } } return -1; } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ publicvoidremove(int key) { inth= hash(key); Iterator<Pair> iterator = data[h].iterator(); while (iterator.hasNext()) { Pairpair= iterator.next(); if (pair.key == key) { data[h].remove(pair); return; } } }
func(m *MyHashMap) hash(key int) int { return key % base }
func(m *MyHashMap) Put(key, value int) { h := m.hash(key) for e := m.data[h].Front(); e != nil; e = e.Next() { if et := e.Value.(entry); et.key == key { e.Value = entry{key, value} return } } m.data[h].PushBack(entry{key, value}) }
func(m *MyHashMap) Get(key int) int { h := m.hash(key) for e := m.data[h].Front(); e != nil; e = e.Next() { if et := e.Value.(entry); et.key == key { return et.value } } return-1 }
func(m *MyHashMap) Remove(key int) { h := m.hash(key) for e := m.data[h].Front(); e != nil; e = e.Next() { if e.Value.(entry).key == key { m.data[h].Remove(e) } } }