代码随想录算法训练营第六天| 242. 有效的字母异位词、349. 两个数组的交集、202. 快乐数、1. 两数之和

242. 有效的字母异位词:


代码思路

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        from collections import defaultdict
        if len(s) != len(t):
            return False
        hashset = defaultdict(int)
        for i in range(len(s)):
            hashset[s[i]] += 1
            hashset[t[i]] -= 1
        for k, v in hashset.items():
            if v < 0:
                return False
        return True

349. 两个数组的交集


代码思路

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        from collections import defaultdict
        hashset1 = defaultdict(int)
        hashset2 = defaultdict(int)
        if len(nums1) < len(nums2):
            long = nums2
            short = nums1
        else:
            long = nums1
            short = nums2
        for i in range(len(long)):
            hashset1[long[i]] += 1
            if i < len(short):
                hashset2[short[i]] += 1
        result = []
        for k, v in hashset1.items():
            if hashset2[k] > 0:
                result.append(k)
        return result
            pre.next = cur.next

202. 快乐数


代码思路

class Solution:
    def isHappy(self, n: int) -> bool:
        from collections import defaultdict
        hashset = defaultdict(int)
        str_nums = str(n)
        while True:
            if hashset[str_nums] > 1:
                return False
            nums = 0
            for i in str_nums:
                nums += int(i) * int(i)
            if nums == 1:
                return True
            hashset[str_nums] += 1
            str_nums = str(nums)

1. 两数之和

代码思路

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        from collections import defaultdict
        hashset = defaultdict(list)
        for i in range(len(nums)):
            hashset[nums[i]].append(i)
        for i in nums:
            find = target - i
            if find == i:
                if len(hashset[find]) > 1:
                    return hashset[find]
            else:
                if len(hashset[find]) > 0:
                    return [hashset[find][0],hashset[i][0]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值