Design HashMap 設計雜湊對映
阿新 • • 發佈:2018-12-13
不使用任何內建的雜湊表庫設計一個雜湊對映
具體地說,你的設計應該包含以下的功能
put(key, value)
:向雜湊對映中插入(鍵,值)的數值對。如果鍵對應的值已經存在,更新這個值。get(key)
:返回給定的鍵所對應的值,如果對映中不包含這個鍵,返回-1。remove(key)
:如果對映中存在這個鍵,刪除這個數值對。
示例:
MyHashMap hashMap = new MyHashMap(); hashMap.put(1, 1); hashMap.put(2, 2); hashMap.get(1); // 返回 1 hashMap.get(3); // 返回 -1 (未找到) hashMap.put(2, 1); // 更新已有的值 hashMap.get(2); // 返回 1 hashMap.remove(2); // 刪除鍵為2的資料 hashMap.get(2); // 返回 -1 (未找到)
注意:
- 所有的值都在
[1, 1000000]
的範圍內。 - 操作的總數目在
[1, 10000]
範圍內。 - 不要使用內建的雜湊庫。
思路:這道題和Design HashSet 設計雜湊集合思路大同小異,只不過我們定義的陣列不再是bool型的,而是int的陣列,初始化為-1,如果需要插入key-value的元素,就array[key]=value,即可。
參考程式碼:
class MyHashMap { public: /** Initialize your data structure here. */ MyHashMap() { memo.resize(1000000,-1); } /** value will always be non-negative. */ void put(int key, int value) { memo[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) { return memo[key]; } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ void remove(int key) { memo[key] = -1; } private: vector<int> memo; }; /** * 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); */