LeetCode | 哈希表

481 字
2 分钟
LeetCode | 哈希表

分类:哈希表 / 总结

讲解#

哈希表题目的核心是:先建一张表,再去表里查东西

两数之和已经遍历过的数字,以及它的下标放进字典作为哈希表,查target - num 在不在表里,最后返回两个数字对应的下标。

字母异位词分组排序后的字符串(key) -> 原字符串列表(value)放进字典作为哈希表,,查当前字符串排序后的 key在不在表里,最后返回字典里所有 value,也就是分好组的字符串列表。

最长连续序列nums 通过set(nums)去重后的所有数字放进集合作为哈希表,查先查 x - 1 在不在确定是不是序列起点,再不断查 x + 1、x + 2、…在不在表里,最后返回最长连续序列的长度。

哈希表题目重要是:我应该把什么变成 key,又要用这个 key 查什么。

代码#

两数之和#

class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
seen = {}
for i, num in enumerate(nums):
need = target - num
if need in seen:
return [seen[need], i]
seen[num] = i
return []

字母异位词分组(排序法)#

from collections import defaultdict
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
mp = defaultdict(list)
for st in strs:
key = "".join(sorted(st))
mp[key].append(st)
return list(mp.values())

最长连续序列#

from typing import List
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
st = set(nums)
m = len(st)
ans = 0
for x in st:
if x - 1 in st:
continue
y = x + 1
while y in st:
y += 1
ans = max(ans, y - x)
if ans * 2 >= m:
break
return ans

参考资料#

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

LeetCode | 哈希表
https://leetcode.cn/tag/hash-table/problemset/
作者
平昊阳
发布于
2026-08-03
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
平昊阳
乘长风,破巨浪, 展鸿图于未央!
--
总访问量
--
访客数
公告
欢迎来到我的个人博客!欢迎关注交流吖!
更多相关公告,见
社交-留言」。
音乐
封面

音乐

暂未播放

0:000:00
暂无歌词
站点统计
文章
66
分类
16
标签
93
总字数
477,284
运行时长
0
最后活动
0 天前

文章目录