Day05 哈希表

242. 有效的字母异位词

解法:因字符串中的字母都是小写单词,只需要长度为26的数组就可以统计所有字母出现的次数。索引就是字母对应的ASCII码减去‘a’的ASCII码,索引对应的值就是字母出现的次数。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        res = [0] * 26
        for i in s:
            res[ord(i) - ord('a')] += 1
        for j in t:
            res[ord(j) - ord('a')] -= 1
        for k in res:
            if k != 0:
                return False
        return True

349. 两个数组的交集

解法:上一题使用数组做哈希表是因为限制了数值的大小。而如果哈希值比较少、特别分散、跨度非常大,使用数组就造成空间的极大浪费。本题没有对数值大小进行限制,因此不可以用数组做哈希表。对于本题我们可以使用字典来做哈希表。

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = dict()
        ans = []

        for i in nums1:
            if res.get(i):
                res[i] += 1
            else:
                res[i] = 1
        
        for j in nums2:
            if j in res.keys():
                ans.append(j)
                res.pop(j)

        return ans

202. 快乐数

解法:题目描述“无限循环”,也就是在求和的过程中,sum可能会重复出现。而当遇到要快速判断一个元素是否出现在集合里的时候,就要考虑哈希表法了。

class Solution(object):
    def get_sum(self, n):
        total = 0
        while n:
            num = n % 10
            total += num ** 2
            n = n // 10
        return total
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        record = set()
        while True:
            n = self.get_sum(n)
            print(n)
            if n == 1:
                return True
            if n in record:
                return False
            else:
                record.add(n)

1. 两数之和

解法:暴力解法的话是两重for循环,时间复杂度为O(n²)。而本题使用哈希表法可以降低时间复杂度。用字典维护一个哈希表,因为字典是key-value结构的,方便存储元素与其下标 。遍历数组,如果(target-元素val)存在于维护的哈希表中,则返回当前元素的下标与(target-元素val)的下标,若不存在,则将当前元素与其下标存入哈希表。另外,使用哈希表降低了时间复杂度,可以少写一个for循环。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        # 1.暴力解法
        # for i in range(len(nums)):
        #     for j in range(i+1, len(nums)):
        #         if nums[i] + nums[j] == target:
        #             return [i, j]

        # 2.利用哈希表 降低了时间复杂度
        # record = dict()
        # for index, val in enumerate(nums):
        #     if target - val not in record:
        #         record[val] = index
        #     else:
        #         return [record[target-val], index]
        # 3.哈希表
        res = dict()
        for i in range(len(nums)):
            rest = target - nums[i]
            if rest in res:
                return [i, res[rest]]
            else:
                res[nums[i]] = i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值