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

242.有效的字母异位词

解法1: hash table
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # method 1
        return collections.Counter(s) == collections.Counter(t)

解法2:排序

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # method 2
        return sorted(s) == sorted(t)

349. 两个数组的交集

解法1:hash+set

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        dic = {}
        res = []
        for i in set(nums1):
            dic[i] = 1
        for j in set(nums2):
            if j in dic:
                res.append(j)
        return res

解法2:set

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:

        return list(set(nums1) & set(nums2))

202. 快乐数

解法1:hash set

细节:无限循环是关键,说明是已经存在过的数字,所以可以用set 来查找

class Solution:
    def isHappy(self, n: int) -> bool:
        def get_number(n):
            total = 0
            while n:
                total += (n % 10)**2
                n //= 10
            return total
        
        
        visited = set()
        while n != 1 and n not in visited:
            visited.add(n)
            n = get_number(n)
        return n == 1

1. 两数之和

解法1:暴力

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        # method 1
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    return [i,j]

解法2:hash

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        # method2
        dir = {}
        for i in range(len(nums)):
            if target - nums[i] not in dir:
                dir[nums[i]] = i
            else:
                return [dir[target - nums[i]],i]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值