不使用任何內建的哈希表庫設計一個哈希映射java
具體地說,你的設計應該包含如下的功能python
put(key, value)
:向哈希映射中插入(鍵,值)的數值對。若是鍵對應的值已經存在,更新這個值。get(key)
:返回給定的鍵所對應的值,若是映射中不包含這個鍵,返回-1。remove(key)
:若是映射中存在這個鍵,刪除這個數值對。Design a HashMap without using any built-in hash table libraries.數組
To be specific, your design should include these functions:bash
put(key, value)
: Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value.get(key)
: Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.remove(key)
: Remove the mapping for the value key if this map contains the mapping for the key.示例:app
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 (未找到)
複製代碼
注意:ui
[1, 1000000]
的範圍內。[1, 10000]
範圍內。Note:this
[0, 1000000]
.[1, 10000]
. 與設計哈希集合一題類似,只須要將布爾類型數組改爲 int 整型數組,元素索引位置爲Key值,元素值爲Value值。spa
題目中要求Key不存在時返回 -1 ,Python中能夠直接初始化值爲 -1 的長度爲 1000001 的數組,直接返回 Value值便可。其餘語言初始化數組後元素值默認爲0,能夠遍歷一遍把值改成 -1,或存儲值爲真實值加 1,返回 Value - 1,若是 Key 不存在時 Value 爲 0,返回 Value - 1 = -1,符合要求。設計
Java:code
class MyHashMap {
private int[] hashMap;
/** Initialize your data structure here. */
public MyHashMap() {
this.hashMap=new int[1000001];
}
/** value will always be non-negative. */
public void put(int key, int value) {
hashMap[key] = value+1;//存儲真實值加 1
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
return hashMap[key] - 1;//返回存儲值爲 -1 獲得真實值
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
hashMap[key] = 0;
}
}
複製代碼
Python:
class MyHashMap:
def __init__(self):
""" Initialize your data structure here. """
self.hash_table = [-1]*1000001
def put(self, key: int, value: int) -> None:
""" value will always be non-negative. """
self.hash_table[key] = value
def get(self, key: int) -> int:
""" Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key """
return self.hash_table[key]#直接返回Value
def remove(self, key: int) -> None:
""" Removes the mapping of the specified value key if this map contains a mapping for the key """
self.hash_table[key] = -1
複製代碼
歡迎關注微.信公.衆號:愛寫Bug