📅  最后修改于: 2023-12-03 15:40:01.338000             🧑  作者: Mango
哈希表是一种基于散列函数实现的数据结构,能够快速地查找和插入数据。哈希表底层是由数组和散列函数组成的,散列函数将键映射到数组中的特定位置。
class ListNode:
def __init__(self, key=None, val=None):
self.key = key
self.val = val
self.next = None
class MyHashMap:
def __init__(self):
self.size = 1000
self.table = [None] * self.size
def put(self, key: int, value: int) -> None:
index = hash(key) % self.size
if not self.table[index]:
self.table[index] = ListNode(key, value)
else:
curr = self.table[index]
while curr:
if curr.key == key:
curr.val = value
return
if not curr.next:
break
curr = curr.next
curr.next = ListNode(key, value)
def get(self, key: int) -> int:
index = hash(key) % self.size
curr = self.table[index]
while curr:
if curr.key == key:
return curr.val
curr = curr.next
return -1
def remove(self, key: int) -> None:
index = hash(key) % self.size
curr = prev = self.table[index]
if not curr:
return
if curr.key == key:
self.table[index] = curr.next
else:
curr = curr.next
while curr:
if curr.key == key:
prev.next = curr.next
return
curr, prev = curr.next, prev.next
以上为Python语言实现哈希表的源代码。