Day06|有效字母异位词、两数组交集、快乐数、两数之和

内容分享2周前发布
0 0 0

哈希表:用于快速判断一个元素是否存在于集合中

有效字母异位词

题目链接:242. 有效的字母异位词 – 力扣(LeetCode)

讲解链接:代码随想录 (programmercarl.com)

    def isAnagram(self, s: str, t: str) -> bool:
        record=[0]*26
        for i in s:
            record[ord(i)-ord( a )]+=1
        for j in t:
            record[ord(j)-ord( a )]-=1
        if any(record):
            return False
        return True

两个数组交集

题目链接:349. 两个数组的交集 – 力扣(LeetCode)

讲解链接:代码随想录 (programmercarl.com)

方法一:使用数组作为hash表(仅适用于元素数量有限情况)

    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        count1 = [0]*1001
        count2 = [0]*1001
        result = []
        for i in range(len(nums1)):
            count1[nums1[i]]+=1
        for j in range(len(nums2)):
            count2[nums2[j]]+=1
        for k in range(1001):
            if count1[k]*count2[k]>0:
                result.append(k)
        return result

方法二:使用字典作为hash表,使用集合储存结果(需要使用集合是为了避免数组中有重复元素时重复输出)

    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
    # 使用哈希表存储一个数组中的所有元素
        table = {}
        for num in nums1:
            table[num] = table.get(num, 0) + 1
        
        # 使用集合存储结果
        res = set()
        for num in nums2:
            if num in table:
                res.add(num)
                del table[num]
        
        return list(res)

方法三:直接利用set结构

    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1) & set(nums2))

快乐数

题目链接:202. 快乐数 – 力扣(LeetCode)

讲解链接:https://programmercarl.com/0202.%E5%BF%AB%E4%B9%90%E6%95%B0.html

关键点:平方求和可能出现两种情况:
1、无限循环
2、变为1
使用hash表的关键思想:判断当前结果是否已经在计算结果中出现过了
用set结构

    def isHappy(self, n: int) -> bool:
        record=set()
        while n!=1:
            n=sum(int(i)*int(i) for i in str(n))
            if n in record:
                return False
            record.add(n)
        return True

两数之和

题目链接:1. 两数之和 – 力扣(LeetCode)

讲解链接:https://programmercarl.com/0001.%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C.html

关键点:由于需要返回索引,故用字典结构作为hash表
*hash映射可以降低时间复杂度的缘由是在字典中查找key时间复杂度为O(1),故总体时间复杂度为O(n)

    def twoSum(self, nums: List[int], target: int) -> List[int]:
        rec={}
        for i in range(len(nums)):
            if target-nums[i] in rec:
                return [i,rec[target-nums[i]]]
            else:
                rec[nums[i]]=i

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
none
暂无评论...