865 字
4 分钟
代码随想录算法训练营第五天 | 哈希表 Part01
哈希表基础
- 哈希表是一种牺牲空间换时间的数据结构,通过哈希函数将键映射到数组索引,实现快速查找。
- 哈希表的查询、插入和删除操作平均时间复杂度为 O(1),在哈希冲突严重的情况下最坏可能退化为 O(n)。
- 常见的三种哈希结构包括:
- 数组(适用于索引范围已知的小写字母等)
- Set(无序、元素唯一)
- Map(键值对)
数组
- 数组常用于当键是连续整数或字符映射为整数的情况,如
'a'
-'z'
对应0
-25
。 - 数组的索引可以直接充当哈希表的键,适合小范围字符或整数的统计场景。
LeetCode 242. 有效的字母异位词
class Solution: def isAnagram(self, s: str, t: str) -> bool: # 由于字母是连续的,并且数量有限(都是小写字母), # 所以可以使用长度为26的数组来统计每个字母出现的次数 # 使用 ord 将字母转换为对应的 ASCII 值,并减去 'a' 的 ASCII 值获取索引 record = [0] * 26
for ch in s: record[ord(ch) - ord('a')] += 1
for ch in t: record[ord(ch) - ord('a')] -= 1
# 若两个字符串是字母异位词,则每个位置上对应的计数应为 0 for count in record: if count != 0: return False
return True
Set
- Set 是一种无序且不重复的集合,适用于快速去重与查找元素是否存在。
- Python 中的
set
底层是哈希表,插入、查找、删除的平均时间复杂度为 O(1)。
LeetCode 349. 两个数组的交集
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: # 使用 set 来存储 nums1 中的元素 # 然后判断 nums2 中哪些元素在 set1 中出现过 # 将交集元素添加到结果集合 set2 中,自动去重 set1 = set(nums1) result_set = set()
for num in nums2: if num in set1: result_set.add(num)
return list(result_set)
LeetCode 202. 快乐数
class Solution: def isHappy(self, n: int) -> bool: # 使用 set 记录出现过的数字,避免无限循环 seen = set()
while True: n = self.get_sum(n) if n == 1: return True # 若当前 n 已出现过,说明进入了循环,返回 False if n in seen: return False seen.add(n)
def get_sum(self, n: int) -> int: # 求每个位置上的数字的平方和 total = 0 while n > 0: n, digit = divmod(n, 10) total += digit ** 2 return total
Map
- Map 是一种键值对形式的数据结构,Python 中使用
dict
表示。 - 适用于快速查找、存储配对信息,如元素与索引、字符与频次等。
- 平均时间复杂度为 O(1),适合大多数查找类题目。
LeetCode 1. 两数之和
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: # 创建一个哈希表,key 为数值,value 为该数值的索引 record = {}
for i, num in enumerate(nums): complement = target - num # 若目标值已存在于哈希表中,返回其索引 if complement in record: return [i, record[complement]] # 将当前数值与索引存入哈希表 record[num] = i
小结与通用提示
-
哈希表适合用于频次统计、快速查找、去重、匹配等操作,常用于:
- 判断元素是否存在
- 元素去重
- 元素配对(如两数之和)
- 检测重复(如快乐数)
-
三种典型使用方式:
- 数组:固定范围内字符/整数映射
- Set:元素去重与存在性判断
- Map:记录键值关系,查找与更新更灵活
代码随想录算法训练营第五天 | 哈希表 Part01
https://fuwari.vercel.app/posts/code_musings_day_five/