【代码随想录训练营】【Day 6】【哈希表-1】| Leetcode 242, 349, 202, 1
需强化知识点
- Python dict 的 get 方法,以及遍历方法
- Python set 会自动去重
题目
242. 有效的字母异位词
- 注意 python ord() 可以直接返回字符的unicode数值,chr() 可以将 unicode值转换为字符
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# record = [0] * 26
# for c in s:
# record[ord(c) - ord('a')] += 1
# for c in t:
# record[ord(c) - ord('a')] -= 1
# for num in record:
# if num != 0:
# return False
# return True
from collections import defaultdict
s_dict = defaultdict(int)
t_dict = defaultdict(int)
for c in s:
s_dict[c] += 1
for c in t:
t_dict[c] += 1
return s_dict == t_dict
349. 两个数组的交集
- python dict 的循环遍历
- python set 增加元素是用add,以及dict删除元素 del,get方法可以替代defaultdict
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
# from collections import defaultdict
# num_dict = defaultdict(int)
# result = []
# for num in nums1:
# num_dict[num] += 1
# for key, value in num_dict.items():
# if key in nums2:
# result.append(key)
# return result
num_dict = {}
for num in nums1:
num_dict[num] = num_dict.get(num, 0) + 1
result = set()
for num in nums2:
if num in num_dict:
result.add(num)
# del num_dict[num]
return list(result)
202. 快乐数
- 注意无限循环停止判定的条件:出现历史上的曾出现的数
class Solution:
def isHappy(self, n: int) -> bool:
def num_square(n):
num_list = []
new_num = 0
while n > 0:
new_num += (n % 10) * (n % 10)
n = n // 10
return new_num
num_dict = {}
while True:
new_num = num_square(n)
if new_num == 1:
return True
if new_num in num_dict:
return False
else:
num_dict[new_num] = 1
n = new_num
1. 两数之和
- 注意hash_dict 加数要在判定之后,不然如果target等于 2*num, 会将自身视为另一个数
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashdict = {}
for index, num in enumerate(nums):
# hashdict[num] = index
if target - num in hashdict:
return [index, hashdict[target-num]]
hashdict[num] = index