每日一题 leetcode 706 设计哈希映射
不使用任何内建的哈希表库设计一个哈希映射(HashMap)。
实现 MyHashMap 类:
MyHashMap() 用空映射初始化对象
void put(int key, int value) 向 HashMap 插入一个键值对 (key, value) 。如果 key 已经存在于映射中,则更新其对应的值 value
int get(int key) 返回特定的 key 所映射的 value ;如果映射中不包含 key 的映射,返回 -1
void remove(key) 如果映射中存在 key 的映射,则移除 key 和它所对应的 value
在Python中可以利用字典来实现这样的功能,非常简单
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.sets = {}
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
self.sets[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
"""
if key in self.sets.keys():
return self.sets[key]
return -1
def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
if key in self.sets.keys():
self.sets.pop(key)
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)