class ListNode:
def __init__(self,key,val):
self.pair = (key,val)
self.next = None
class MyHashMap:
"""main idea: chaining
"""
def __init__(self):
self.m = 1000
self.table = [None]*self.m
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
1. get hcode
2. check if self.table[h] empty: if yes, plug otherwise, find the exact key and update value. if no same key found, plug in the end
"""
h = key%self.m
if not self.table[h] :
self.table[h] = ListNode(key,value)
return
node = self.table[h]
prev = None
while node:
if node.pair[0] == key:
node.pair = (key,value)
return
prev = node
node = node.next
prev.next = ListNode(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
1. get hcode
2. check all keys at hcode position until find exact key
"""
h = key % self.m
if not self.table[h]:
return -1
node = self.table[h]
while node:
if node.pair[0] == key:
return node.pair[1]
node = node.next
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
1. get hcode
2. chekc if head's key is target key: yes -> leave second listnode as head; no -> loop until find the exact node with the same key; meanwhile save current node's prev node until remove current node
"""
h = key % self.m
if not self.table[h]:
return
node = self.table[h]
if node.pair[0] == key:
self.table[h] = node.next
return
prev = node
while node:
if node.pair[0] == key:
prev.next = node.next
return
prev = node
node = node.next
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)