代码随想录 第六天

第一题 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
相关推荐
2301_8227032014 小时前
Flutter 框架跨平台鸿蒙开发 - 创意声音合成器应用
算法·flutter·华为·harmonyos·鸿蒙
cmpxr_15 小时前
【C】数组名、函数名的特殊
c语言·算法
KAU的云实验台15 小时前
【算法精解】AIR期刊算法IAGWO:引入速度概念与逆多元二次权重,可应对高维/工程问题(附Matlab源码)
开发语言·算法·matlab
会编程的土豆15 小时前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
大熊背16 小时前
如何利用Lv值实现三级降帧
算法·自动曝光·lv·isppipeline
大尚来也16 小时前
驾驭并发:.NET多线程编程的挑战与破局之道
java·前端·算法
向阳而生,一路生花16 小时前
深入浅出 JDK7 HashMap 源码分析
算法·哈希算法
君义_noip17 小时前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
摸个小yu17 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表