代码随想录 第六天

第一题 https://leetcode.cn/problems/valid-anagram/description/

简单 可以用26位数组模拟哈希表

python 复制代码
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        map = [0] * 26
        for i in range(len(s)):
            map[ord(s[i]) - ord('a')] += 1
            map[ord(t[i]) - ord('a')] -= 1
        if self.allZero(map):
            return True
        else:
            return False

    def allZero(self, list):
        for char in list:
            if char != 0:
                return False
        return True

第二题 https://leetcode.cn/problems/intersection-of-two-arrays/description/ 求交集

python 复制代码
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1) & set(nums2))

python是强大,一行就写完了 https://leetcode.cn/problems/intersection-of-two-arrays-ii/description/

这个是进阶版本的题目

python 复制代码
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # 统计两个数组中每个数字出现的次数
        cnt1 = Counter(nums1)  # 例如:nums1=[1,2,2,3] -> Counter({2: 2, 1: 1, 3: 1})
        cnt2 = Counter(nums2)  # 例如:nums2=[2,2,3] -> Counter({2: 2, 3: 1})

        # & 运算取交集,保留较小计数
        inter = cnt1 & cnt2    # 结果:Counter({2: 2, 3: 1})
        # 解释:数字 2 在两个数组中都有,出现次数取较小值 2
        #       数字 3 在两个数组中都有,出现次数取较小值 1

        ans = []
        # 将结果展开成列表
        for num, freq in inter.items():
            ans.extend([num] * freq)  # 例如:[2] * 2 = [2, 2]
        return ans  # 返回:[2, 2, 3]

注意append和extend的区别

第三题 快乐数 https://leetcode.cn/problems/happy-number/

python 复制代码
class Solution:
    def isHappy(self, n: int) -> bool:
        seen = set()

        while n != 1 and n not in seen:
            seen.add(n)
            n = sum(int(dight) ** 2 for dight in str(n))

        return n == 1

有可能陷入无限循环,从这受启发应该用set

第四题 https://leetcode.cn/problems/two-sum/ 力扣第一题,学过哈希表的话应该还是很明显能想到用哈希表

python 复制代码
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        map = {}
        for i in range(len(nums)):
            if target - nums[i] in map:
                return [map.get(target - nums[i]), i]
            map[nums[i]] = i
        return None
相关推荐
风筝在晴天搁浅1 分钟前
字节高频题 小于n的最大数
算法
LabVIEW开发3 分钟前
LabVIEW水力机组空蚀在线监测
算法·labview·labview知识·labview功能·labview程序
AI科技星9 分钟前
科幻艺术书本封面:《全域数学》第一部·数术本源 第三卷 代数原本(P95-141)完整五级目录【乖乖数学】
算法·机器学习·数学建模·数据挖掘·量子计算
风筝在晴天搁浅11 分钟前
LeetCode 92.反转链表Ⅱ
算法·leetcode·链表
王老师青少年编程24 分钟前
csp信奥赛C++高频考点专项训练之贪心算法 --【贪心与二分判定】:数列分段 Section II
c++·算法·贪心·csp·信奥赛·二分判定·数列分段 section ii
V搜xhliang02461 小时前
OpenClaw科研全场景用法:从文献到实验室的完整自动化方案
运维·开发语言·人工智能·python·算法·microsoft·自动化
汉克老师1 小时前
GESP2025年3月认证C++五级( 第三部分编程题(2、原根判断))
c++·算法·模运算·gesp5级·gesp五级·原根·分解质因数
数据皮皮侠1 小时前
上市公司创新韧性数据(2000-2024)|顶刊同款 EIR 指数
大数据·人工智能·算法·智慧城市·制造
WL_Aurora1 小时前
Python 算法基础篇之链表
python·算法·链表
科研前沿2 小时前
纯视觉无感解算 + 动态数字孪生:室内外无感定位技术全新升级
大数据·人工智能·算法·重构·空间计算