代码随想录d6打卡:有效的字母异位词、两数之和、两个数组的交集、快乐数

有效的字母异位词

刷题日期:2024-04-22
[[242.有效的字母异位词]]

思路

哈希表

算法思路

看题设如果数据范围固定则可以考虑哈希表

算法细节

1.

Code

我多创建了一个数组并逐个比较, 实际上只创建一个数组即可, 最后验证数组内有没有不为零的值.

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        t_dict = [0] * 26
        s_dict = [0] * 26

        for i in range(len(t)):
            t_dict[ord(t[i]) - ord('a')] += 1

        for i in range(len(s)):
            s_dict[ord(s[i]) - ord('a')] += 1

        for i in range(26):
            if t_dict[i] != s_dict[i]:
                return False

        return True

两数之和

刷题日期:2024-04-22
[[001.两数之和]]

思路

使用dict

算法思路

遍历数组, 查找dict中有无目标数值, 若没有则使用dict保存遍历过的值和对应索引, 若有则直接返回索引
但实际上可以直接用py中list的方法, 直接查找有无目标值, 若有的话直接返回索引

算法细节

1.

Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            search = target - nums[i]
            if search in nums[i + 1:]:
                return [i, i + 1 + nums[i + 1:].index(search)]

两个数组的交集

刷题日期:2024-04-22
[[349. 两个数组的交集]]

思路

哈希表

算法思路

将数组1转换为set格式, 遍历数组2, 若有重复元素则添加到set类型的result中, 最后将result转换为list输出

算法细节

1.

Code

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

        for i in nums1:
            if not i in num1_set:
                num1_set.add(i)

        for i in nums2:
            if i in num1_set:
                result.add(i)

        return list(result)

快乐数

刷题日期:2024-04-22
[[202.快乐数]]

思路

set保存出现过的数

算法思路

题目中提到了会无限循环, 便考虑到使用set保存出现过的数, 一旦循环则推出while, 判断n的值

算法细节

1.

Code

class Solution:
    def isHappy(self, n: int) -> bool:
        n_set = set()
        while not n in n_set:
            n_set.add(n)
            digits = [int(char) for char in str(n)]
            temp = 0
            for i in digits:
                temp += int(i) ** 2
            n = temp

        if n == 1:
            return True
        else:
            return False
  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值