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
。
示例:
输入: ["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] [[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]] 输出: [null, null, null, 1, -1, null, 1, null, -1] 解释: MyHashMap myHashMap = new MyHashMap(); myHashMap.put(1, 1); // myHashMap 现在为 [[1,1]] myHashMap.put(2, 2); // myHashMap 现在为 [[1,1], [2,2]] myHashMap.get(1); // 返回 1 ,myHashMap 现在为 [[1,1], [2,2]] myHashMap.get(3); // 返回 -1(未找到),myHashMap 现在为 [[1,1], [2,2]] myHashMap.put(2, 1); // myHashMap 现在为 [[1,1], [2,1]](更新已有的值) myHashMap.get(2); // 返回 1 ,myHashMap 现在为 [[1,1], [2,1]] myHashMap.remove(2); // 删除键为 2 的数据,myHashMap 现在为 [[1,1]] myHashMap.get(2); // 返回 -1(未找到),myHashMap 现在为 [[1,1]]
提示:
0 <= key, value <= 10
6
- 最多调用
10
4
次put
、get
和remove
方法
通过次数75,176提交次数117,610
法1 拉链法
思路
拉链法,指的是,把 key 按照某个数 buckets 的余数,把 key 放进 buckets 个小桶里。在这个小桶里,像拉链一样,藏着很多 key % buckets 相等的 key 值,对应着这个 key 的,就是相应的 value。这就相当于,把 key 按照余数先分了个类,定位这个类的时间复杂度为 O(1),但接下来去找拉链,就要一个一个地找了。这样,就在时间和存储 key 需要的空间上做出了权衡。其中,buckets 一般取质数,余数的分布会均匀一些。
题解
class MyHashMap: def __init__(self): """ Initialize your data structure here. """ self.buckets = 1009 self.table = [[] for _ in range(self.buckets)] def put(self, key: int, value: int) -> None: """ value will always be non-negative. """ hashkey = key % self.buckets for item in self.table[hashkey]: if item[0] == key: item[1] = value return self.table[hashkey].append([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 """ hashkey = key % self.buckets for item in self.table[hashkey]: if item[0] == key: return item[1] 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 """ hashkey = key % self.buckets for i, item in enumerate(self.table[hashkey]): if item[0] == key: self.table[hashkey].pop(i) # Your MyHashMap object will be instantiated and called as such: # obj = MyHashMap() # obj.put(key,value) # param_2 = obj.get(key) # obj.remove(key)