哈希表理论基础
建议:大家要了解哈希表的内部实现原理,哈希函数,哈希碰撞,以及常见哈希表的区别,数组,set 和map。
什么时候想到用哈希法,当我们遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希法。 这句话很重要,大家在做哈希表题目都要思考这句话。
文章讲解:代码随想录
242.有效的字母异位词 ✅
建议: 这道题目,大家可以感受到 数组 用来做哈希表 给我们带来的便利之处。
题目链接/文章讲解/视频讲解: 代码随想录
# 242
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
record = [0] * 26
for i in range(len(s)):
record[ord(s[i]) - ord('a')] += 1
for i in range(len(t)):
record[ord(t[i]) - ord('a')] -= 1
for i in range(26):
if record[i] != 0: return False
return True
注意python中字符到ASCII的转换要用ord('a')!
相关题目:
349. 两个数组的交集 ✅
建议:本题就开始考虑 什么时候用set 什么时候用数组,本题其实是使用set的好题,但是后来力扣改了题目描述和 测试用例,添加了 0 <= nums1[i], nums2[i] <= 1000 条件,所以使用数组也可以了,不过建议大家忽略这个条件。 尝试去使用set。
题目链接/文章讲解/视频讲解:代码随想录
# 349
# set
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = set()
num_set = set(nums1)
for num in nums2:
if num in num_set:
result.add(num)
return list(result)
# 349
# 数组
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = set()
num_set = [0] * 1002
for num in nums1:
num_set[num] = 1
for num in nums2:
if num_set[num] == 1:
result.add(num)
return list(result)
⚠️注意一下和cpp语法的不同,用set就可以了
⚠️把set转为列表,用的是list()
相关题目:
202. 快乐数 AC
建议:这道题目也是set的应用,其实和上一题差不多,就是 套在快乐数一个壳子
题目链接/文章讲解:代码随想录
# 202
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
record = set()
while True:
n = self.get_sum(n)
if n == 1:
return True
# 如果中间结果重复出现,说明陷入死循环了,该数不是快乐数
if n in record:
return False
else:
record.add(n)
def get_sum(self, n):
new_num = 0
while n:
n, r = divmod(n, 10)
new_num += r ** 2
return new_num
函数get_sum()中:n, r = divmod(n, 10)意味着当n不是0时 divide n by 10, setting n to the quotient and r to the remainder (the last digit of n) 。这个loop就是求每一位数字平方和的方法!
1. 两数之和 ✅
建议:本题虽然是 力扣第一题,但是还是挺难的,也是 代码随想录中 数组,set之后,使用map解决哈希问题的第一题。
建议大家先看视频讲解,然后尝试自己写代码,在看文章讲解,加深印象。
题目链接/文章讲解/视频讲解:代码随想录
# 1
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
record = dict()
for i in range(len(nums)):
search = target - nums[i]
if search in record:
return [record[search], i]
record[nums[i]] = i
return None
*Python 还可以用这种遍历列表的方式写:for index, value in enumerate(nums),这个enumerate() 特别好用!!
总结



这里时间复杂度看得不是很明白

本文探讨了哈希表的基础知识及其在解决算法问题中的应用,包括242题的有效字母异位词、349题的两个数组交集和202题的快乐数。通过哈希表,可以快速判断元素出现、计算交集以及判断快乐数。同时,文章提到了在不同场景下选择使用数组、set或map的策略,并给出了相关题目的解题建议和链接。

被折叠的 条评论
为什么被折叠?



