1. 程式人生 > >leetcode 706. 設計雜湊對映(python)

leetcode 706. 設計雜湊對映(python)

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

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

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


注意:

  • 所有的值都在 [1, 1000000]的範圍內。
  • 操作的總數目在[1, 10000]範圍內。
  • 不要使用內建的雜湊庫。
class MyHashMap(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.buckets = 1000
        self.itemsPerBuckect = 1001
        self.hashmap = [[] for _ in range(self.buckets)]
    
    def hash(self, key):
        return key % self.buckets

    def pos(self, key):
        return key // self.buckets        

    def put(self, key, value):
        """
        value will always be positive.
        :type key: int
        :type value: int
        :rtype: void
        """
        hashkey = self.hash(key)
        if not self.hashmap[hashkey]:
            self.hashmap[hashkey] = [None] * self.itemsPerBuckect
        self.hashmap[hashkey][self.pos(key)] = value
        
        

    def get(self, key):
        """
        Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
        :type key: int
        :rtype: int
        """
        hashkey = self.hash(key)
        if (not self.hashmap[hashkey]) or self.hashmap[hashkey][self.pos(key)] == None:
            return -1
        else:
            return self.hashmap[hashkey][self.pos(key)]

        

    def remove(self, key):
        """
        Removes the mapping of the specified value key if this map contains a mapping for the key
        :type key: int
        :rtype: void
        """
        hashkey = self.hash(key)
        if self.hashmap[hashkey]:
            self.hashmap[hashkey][self.pos(key)] = None

        


# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)