題目描述
不使用任何內建的哈希表庫設計一個哈希映射
具體地說,你的設計應該包含以下的功能
put(key, value):向哈希映射中插入(鍵,值)的數值對。如果鍵對應的值已經存在,更新這個值。
get(key):返回給定的鍵所對應的值,如果映射中不包含這個鍵,返回-1。
remove(key):如果映射中存在這個鍵,刪除這個數值對。
注意:所有的值都在 [0, 1000000]的範圍內。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/design-hashmap
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
算法思路
哈希映射的基礎就是哈希集合,在【力扣日記】705 設計哈希集合的基礎上隨便改改就得到哈希映射了。
class MyHashMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.keyRange = 769 #確定桶的數量
self.bucketArray = [Bucket() for i in range(self.keyRange)]
def _hash(self, key):
return key % self.keyRange
def put(self, key,value):
"""
:type key: int
:rtype: None
"""
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].insert(key,value)
def remove(self, key):
"""
:type key: int
:rtype: None
"""
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].delete(key)
def get(self, key):
"""
Returns true if this set contains the specified element
:type key: int
:rtype: bool
"""
bucketIndex = self._hash(key)
fg= self.bucketArray[bucketIndex].exists(key)
if fg==-1:return-1
return fg.value
class Node:# 鏈表作爲容器
def __init__(self, key,value=0, nextNode=None):
self.key=key
self.value = value
self.next = nextNode
class Bucket:# 桶的定義
def __init__(self):
# a pseudo head
self.head = Node(0)
def insert(self, key,newValue):
# if not existed, add the new element to the head.
fg=self.exists(key)
if fg==-1:
newNode = Node(key,newValue, self.head.next)
# set the new head.
self.head.next = newNode
else:
fg.value=newValue
def delete(self, key):
prev = self.head
curr = self.head.next
while curr is not None:
if curr.key == key:
# remove the current node
prev.next = curr.next
return
prev = curr
curr = curr.next
def exists(self, key):
curr = self.head.next
while curr is not None:
if curr.key == key:
# value existed already, do nothing
return curr
curr = curr.next
return -1
執行用時 :340 ms, 在所有 Python3 提交中擊敗了39.80%的用戶
內存消耗 :17 MB, 在所有 Python3 提交中擊敗了100.00%的用戶