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


学习链接:https://programmercarl.com/哈希表理论基础.html

学习笔记:

遇到“要判断一个值是否在集合中出现过”的问题时,可以考虑hash表。

hash表的形式包括数组、set、dict。当数的位数比较统一、或比较小,可用数组,快;当数的位数可变,可用set;当要同时考虑数的下标和值,可以用dict。

我的解答过程:

242.有效的字母异位词(用的数组作hash表,只需知道字母与‘a’的差,不用知道具体ASCII码)

点击查看代码
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        record=[0]*26
        for i in s:
            record[ord(i)-ord('a')] += 1
        for i in t:
            record[ord(i)-ord('a')] -= 1
        for i in range(26):
            if record[i] != 0:
                return False
        return True

349.两个数组的交集(用的dict作hash表,结果用set避免重复)

点击查看代码
class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        result = set()
        hash_dict = {}
        for i in nums1:
            hash_dict[i]=hash_dict.get(i, 0)+1
        for i in nums2:
            if i in hash_dict:
                result.add(i)
                del hash_dict[i]
        return list(result)
202.快乐数(用set作hash表,把数字转换为str来遍历每一位上的数字,无限循环用while,当循环得到同一个n代表不快乐要跳出循环)
点击查看代码
class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        record=set()
        while n not in record:
            record.add(n)
            new_n = 0
            str_n = str(n)
            for i in str_n:
                new_n += int(i)**2
            if new_n == 1:
                return True
            else:
                n = new_n

        return False
1.两数之和(用dict作hash表,查找目标值与当前值的差是否在hash表里,用值作为dict的键,下标作dict的值)
点击查看代码
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        result=dict()
        for i, value in enumerate(nums):
            if target-value in result:
                return [result[target-value], i]
            result[value]=i
        return []
PS:

我都用Python解题。其实今天是我第一天学习,加油!

posted @   Tristan241001  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示