代码随想录训练营第III期--006(005休息)--python

# 代码随想录训练营第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 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

deyiwang89

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值