March-706. Design hash mapping

 

class MyHashMap:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        #self.hashmap = dict()
        #self.hashmap = [-1]*1000001
        self.map = [[-1] * 1000 for _ in range(1001)]

    def put(self, key: int, value: int) -> None:
        """
        value will always be non-negative.
        """
        #self.hashmap[key]=value
        row,col = key//1000,key%1000
        self.map[row][col] = 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.hashmap:
        #     return self.hashmap[key]
        # else:
        #     return -1

        #return self.hashmap[key]

        row,col = key//1000, key%1000
        return self.map[row][col]    
    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:
        #     del self.hashmap[key]
        #self.hashmap[key]=-1

        row,col = key//1000, key%1000
        self.map[row][col]=-1    
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)

In fact, this question is an implementation of the source code of hash mapping.

  • It is relatively simple to directly call the encapsulated dictionary. AC can be used but the point of investigation for this question is not answered
  • Use a super large array, the index of the super large array is the key, and the value of the array is the value
  • Use a relatively small two-dimensional array, this advantage class is similar to hash conflict mapping, there may be several mappings in a key, then we use the second dimension of the array to do a process, so that we can accurately get the value Up
    • row-hash bucket-key//1000
    • col-Find the specific location where the key is stored-key%1000
    • The purpose of this is to save space, which is called the fixed-length zipper method 

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/114853774