[Hash-Simple] 706. Design a hash map (array method + zipper method (fixed-length zipper + variable-length zipper))

[Title]
Design a hash map (HashMap) without using any built-in hash table library.
Realize the MyHashMap class:
MyHashMap() Initialize the object with a null map
void put(int key, int value) Insert a key-value pair (key, value) into the HashMap. If the key already exists in the map, update its corresponding value value.
int get(int key) Returns the value mapped by the specific key; if the mapping does not contain the key mapping, it returns -1.
void remove(key) If there is a key mapping in the mapping, remove the key and its corresponding value.
[Example]
Input:
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
[[], [1, 1 ], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
Output:
[null, null, null, 1, -1, null, 1, null, -1]
Explanation:
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // myHashMap is now [[1,1]]
myHashMap.put(2, 2); // myHashMap It is now [[1,1], [2,2]]
myHashMap.get(1); // returns 1, myHashMap is now [[1,1], [2,2]]
myHashMap.get(3); // returns -1 (not found), myHashMap is now [[ 1,1], [2,2]]
myHashMap.put(2, 1); // myHashMap is now [[1,1], [2,1]] (update existing values)
myHashMap.get(2 ); // return 1, myHashMap is now [[1,1], [2,1]]
myHashMap.remove(2); // delete the data with key 2, myHashMap is now [[1,1]]
myHashMap .get(2); // returns -1 (not found), myHashMap is now [[1,1]]
[Prompt]
0 <= key, value <= 106
calls up to 104 put, get and remove methods to
advance : Can you solve this problem without using the built-in HashMap library?
[Code]
[Python]
Insert picture description here

class MyHashMap:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.myhashmap=[]
        

    def put(self, key: int, value: int) -> None:
        """
        value will always be non-negative.
        """
        flag=1
        for k in self.myhashmap:
            if key==k[0]:
                k[1]=value
                flag=0
        if flag:
            self.myhashmap.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
        """
        for k in self.myhashmap:
            if key==k[0]:
                return k[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
        """
        for index,k in enumerate(self.myhashmap):
            if k[0]==key:
                self.myhashmap.pop(index)


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

[Method 2: Time for space]
Insert picture description here

class MyHashMap:
    def __init__(self):
        self.myhashmap=[-1]*1000001

    def put(self, key: int, value: int) -> None:
        self.myhashmap[key]=value

    def get(self, key: int) -> int:
        return self.myhashmap[key]
        
    def remove(self, key: int) -> None:
        self.myhashmap[key]=-1

【Fixed Length Zipper Method】
Insert picture description here

class MyHashMap:
    def __init__(self):
        self.myhashmap=[[-1]*1000 for _ in range(1001)]
    def put(self, key: int, value: int) -> None:
        self.myhashmap[key//1000][key%1000]=value
    def get(self, key: int) -> int:
        return self.myhashmap[key//1000][key%1000]
    def remove(self, key: int) -> None:
        self.myhashmap[key//1000][key%1000]=-1

[ Indefinite length zipper method ] The
variable length zipper array means that the zipper will dynamically grow according to the keys in the bucket, which is more similar to a real linked list.
The number of buckets is generally prime. This is because empirically speaking, the bucketing of prime numbers allows data to be more dispersed in each bucket. In the following code, the number of buckets is reduced to 1009 because 1009 is the first prime number greater than 1000.
Advantages: saving memory, no need to predict the range of data;
disadvantages: searching for elements in the linked list requires traversal.
Insert picture description here

class MyHashMap:

    def __init__(self):
        self.buckets = 1009
        self.table = [[] for _ in range(self.buckets)]

    def hash(self, key):
        return key % self.buckets
    
    def put(self, key: int, value: int) -> None:
        hashkey = self.hash(key)
        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:
        hashkey = self.hash(key)
        for item in self.table[hashkey]:
            if item[0] == key:
                return item[1]
        return -1

    def remove(self, key: int) -> None:
        hashkey = self.hash(key)
        for i, item in enumerate(self.table[hashkey]):
            if item[0] == key:
                self.table[hashkey].pop(i)
                return

Guess you like

Origin blog.csdn.net/kz_java/article/details/115049073