# 代码随想录训练营第III期--006(005休息)--python
# ● 哈希表理论基础
print('check')
# ● 242.有效的字母异位词
import collections
def isAnagram(s,t):
tmp_d = collections.defaultdict(int)
for i in s:
tmp_d[i] += 1
for j in t:
if j in tmp_d.keys():
tmp_d[j] -= 1
if tmp_d[j] < 0: return False# case 'aacc' 'ccac'
else: return False
print(tmp_d.items())
return sum(tmp_d.values()) == 0
s = "aacc"
t = "ccac"
print(isAnagram(s,t))
# ● 349. 两个数组的交集
def intersection(nums1: list[int], nums2: list[int]) -> List[int]:
if len(nums1) < len(nums2):
tmp = nums1
nums1 = nums2
nums2 = tmp
tmp_d = collections.defaultdict(int)
for i in nums2:
tmp_d[i] += 1
res = set()
for i in nums1:
if i in tmp_d.keys():
res.add(i)
return list(res)
# ● 202. 快乐数
# 记得以前是设定一个最大递归次数,然后递归到1时return True, 超时就return False
# 要用位运算,而不是利用str->int的模式进行运算这样肯定比较慢
def isHappy(n: int) -> bool:
def cal(num):
ans = 0
while num:
ans += (num%10)**2
num = num // 10
return ans
ans_d = collections.defaultdict(int)
while True:
n = cal(n)
if n == 1: return True
else:
if n in ans_d.keys(): return False
else:
ans_d[n] += 1
# ● 1. 两数之和
def twoSum(nums, target: int):
res = collections.defaultdict(int)
for idx, val in enumerate(nums):
if target - val in res.keys():
# 这里有个坑,就是[3,3]的时候,会重复记录,
# 因此要把对dict的检索放到前面,
# 然后再进行保存
return [res[target-val], idx]
res[val] = idx
代码随想录训练营第III期--006(005休息)--python
最新推荐文章于 2024-07-23 14:36:35 发布