1. 程式人生 > 實用技巧 >706. 設計雜湊對映

706. 設計雜湊對映

不使用任何內建的雜湊表庫設計一個雜湊對映

具體地說,你的設計應該包含以下的功能

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 (未找到)

注意:

所有的值都在[0, 1000000]的範圍內。
操作的總數目在[1, 10000]範圍內。
不要使用內建的雜湊庫。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/design-hashmap
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

class MyHashMap:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.hashMap={}
        

    def
put(self, key: int, value: int) -> None: """ value will always be non-negative. """ self.hashMap[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.hashMap.get(key,-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.hashMap: self.hashMap.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)