哈希表:
散列表
key : value
- 数组实现
- java - hashmap
- python - 字典
key -> 哈希函数 -> 内存地址 -> key/value对应的内存地址
- 哈希碰撞:2个不同的key通过同一个哈希函数得到相同的内存地址
链表解决哈希碰撞
时间复杂度
- 访问Access — X
- 搜索Search — O(1) — 碰撞情况 — O(k) — k为碰撞元素的个数
- 插入Insert — O(1)
- 删除Delete — O(1) — 碰撞情况
常用操作
-
创建哈希表
hashTable = [ ’ ’ ]*4
–
mapping = { }
– -
添加元素
学号:姓名
O(1)
–
hashTable[1] = ‘hanmeimei’
hashTable[2] = ‘lihua’
hashTable[3] = ‘siyangyuan’
–
mapping[1] = ‘hanmeimei’
mapping[2] = ‘lihua’
mapping[3] = ‘siyangyuan’
– -
删除元素
hashTable[1] = ’ ’
–
mapping.pop(1)
(key)
–
del mapping[1]
– -
修改元素
hashTable[1] = ‘bishi’
–
mapping[1] = ‘bishi’
O(1)
– -
获取key的value
hashTable[3]
–
mapping[3]
O(1)
– -
检测key是否存在
3 in mapping
O(1)
– -
哈希表长度以及哈希表是否还有元素
len(mapping) == 0
O(1)
练习题
- 217 . 存在重复元素
class Solution:
# Hash map
# Time complexity: O(N)
# Space complexity: O(N)
def containsDuplicate(self, nums: List[int]) -> bool:
if len(nums) == 0:
return False
mapping = {}
for num in nums:
if num not in mapping:
mapping[num] = 1
else:
mapping[num] = mapping.get(num) + 1
for v in mapping.values():
if v > 1:
return True
return False
- 389 . 找不同
class Solution:
# Hash Table
# N is the size of t
# Time complexity: O(N)
# Space complexity: O(N)
def findTheDifference(self, s: str, t: str) -> str:
if len(s) == 0:
return t
table = [0]*26
for i in range(len(t)):
if i < len(s):
table[ord(s[i])-ord('a')] -= 1
table[ord(t[i]-ord('a')] += 1
for i in range(26):
if table[i] != 0:
return chr(i+97)
return 'a'
- 496 . 下一个更大元素
class Solution:
# Stack
# M is the size of nums1, N is the size of nums2
# Time Complexity: O(M+N)
# Space Complexity: O(N)
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = []
stack = []
mapping = {}
for num in nums2:
while len(stack) != 0 and num > stack[-1]:
temp = stack.pop()
mapping[temp] = num
stack.append(num)
while len(stack) != 0:
mapping[stack.pop()] = -1
for num in nums1:
res.append(mapping[num])
return res
学习视频来源B站—爱学习的饲养员—手把手带你刷Leetcode力扣