哈希
解决哈希碰撞的方法:
- 拉链法:链表
- 线性探测法:冲突的用下一个位置来放
哈希的底层实现还不是很明白
242. 有效的字母异位词
- python里面使用哈希表,使用dict或者defaultdict或者{}
- table[num] = table.get(num, 0) + 1。这样就不用if判断是否在哈希表里了。table.get(num, 0),不存在就是0
- 计算字符串中字母出现的次数可以使用Counter
- ACII码的计算:ord(i) - ord(“a”)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# 1. 使用dict:dict和defaultdict有啥区别
count_s = dict()
count_t = dict()
for i in s:
if i in count_s:
count_s[i] += 1
else:
count_s[i] = 1
# table[num] = table.get(num, 0) + 1
for i in t:
if i in count_t:
count_t[i] += 1
else:
count_t[i] = 1
return count_s == count_t
# 2。使用counter
count_s = Counter(s)
count_t = Counter(t)
return count_s == count_t
# 3. 26个字母分别记录.
# ACII码的计算:ord(i) - ord("a")
349. 两个数组的交集
- 几个小优化:table[num] = table.get(num, 0) + 1
- 只需要第一个nums1构建哈希表,nums2遍历的时候去哈希表找就行,不需要两个nums都构建哈希表,可以减少一次遍历
- del table[num]
代码随想录的解答:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
# 使用哈希表存储一个数组中的所有元素
table = {}
for num in nums1:
table[num] = table.get(num, 0) + 1
# 使用集合存储结果
res = set()
for num in nums2:
if num in table:
res.add(num)
del table[num]
return list(res)
自己写的:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
count1 = Counter(nums1)
count2 = Counter(nums2)
output = []
for i in count1:
if i in count2:
output.append(i)
return output
202. 快乐数
- 为了防止循环需要把sum记录下来,出现循环就表示不是快乐数
class Solution:
def isHappy(self, n: int) -> bool:
sum = 0
sum_set = set()
while(sum != 1):
sum = 0
for i in str(n):
sum += int(i)**2
if sum in sum_set:
return False
else:
sum_set.add(sum)
n = sum
return True
1. 两数之和
- 原来第一题这么难的吗。一时还没想到非暴力的解法。
- 用dict来记录遍历过的数字,之后就可以用哈希表查找了,可以防止再遍历一遍,用空间O(n)换时间O(n)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_set = dict()
for i in range(len(nums)):
find = target - nums[i]
if find in num_set:
return [num_set.get(find), i]
num_set[nums[i]] = i # key是数字,value是位置