題目:
不使用任何內建的哈希表庫設計一個哈希映射
具體地說,你的設計應該包含以下的功能
-
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:
-
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.
示例:
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]
範圍內。 - 不要使用內建的哈希庫。
Note:
- All keys and values will be in the range of
[0, 1000000]
. - The number of operations will be in the range of
[1, 10000]
. - Please do not use the built-in HashMap library.
解題思路:
與設計哈希集合一題相似,只需要將布爾類型數組改成 int 整型數組,元素索引位置爲Key值,元素值爲Value值。
題目中要求Key不存在時返回 -1 ,Python中可以直接初始化值爲 -1 的長度爲 1000001 的數組,直接返回 Value值即可。其他語言初始化數組後元素值默認爲0,可以遍歷一遍把值改爲 -1,或存儲值爲真實值加 1,返回 Value - 1,如果 Key 不存在時 Value 爲 0,返回 Value - 1 = -1,符合要求。
代碼:
Java:
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