Leetcode 打卡 day5

哈希表

哈希理论基础

当我们遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希法。 这句话很重要,大家在做哈希表题目都要思考这句话。

242. 有效的字母异位词

方法1

1、使用Python库, from collections import defaultdict;

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        from collections import defaultdict
        s_dict = defaultdict(int)
        t_dict = defaultdict(int)
        for i in s:
            s_dict[i] += 1
        for j in t:
            t_dict[j] += 1
        return s_dict == t_dict

方法2

1、使用数组作为哈希表,但是要注意,使用数组来做哈希的题目,是因为题目都限制了数值的大小。
数组其实就是一个简单哈希表,而且这道题目中字符串只有小写字符,那么就可以定义一个数组,来记录字符串s里字符出现的次数。

2、定义一个数组叫做records用来上记录字符串s里字符出现的次数。
需要把字符映射到数组也就是哈希表的索引下标上,因为字符a到字符z的ASCII是26个连续的数值,所以字符a映射为下标0,相应的字符z映射为下标25。
再遍历 字符串s的时候,只需要将 s[i] - ‘a’ 所在的元素做+1 操作即可,并不需要记住字符a的ASCII,只要求出一个相对数值就可以了。 这样就将字符串s中字符出现的次数,统计出来了。
那看一下如何检查字符串t中是否出现了这些字符,同样在遍历字符串t的时候,对t中出现的字符映射哈希表索引上的数值再做-1的操作。
那么最后检查一下,records数组如果有的元素不为零0,说明字符串s和t一定是谁多了字符或者谁少了字符,return false。
最后如果records数组所有元素都为零0,说明字符串s和t是字母异位词,return true。
时间复杂度为O(n),空间上因为定义的是一个常量大小的辅助数组,所以空间复杂度为O(1)。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        records = [0] * 26
        for i in range(len(s)):
            records[ord(s[i])-ord('a')] += 1
        for j in range(len(t)):
            records[ord(t[j])-ord('a')] -= 1
        for i in range(len(records)):
            if records[i] != 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]
        """
        set1 = set(nums1)
        set2 = set(nums2)
        res = list(set1 & set2)
        return res
        # 简化版 return list(set(nums1) & set(nums2))

202. 快乐数

1、自建个函数isHappyNumber来计算每个位数上数字的平方和
2、用集合记录每次计算的每个位数上数字的平方和,如果中间结果重复出现,说明陷入死循环了,该数不是快乐数。

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

1. 两数之和

方法1:
使用两个for循环来输出满足条件的下标。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i,item1 in enumerate(nums):
            for j,item2 in enumerate(nums):
                if i!=j:
                    sum =item1 +item2
                    if sum ==target:
                        return [i,j]

方法2:
使用字典记录target目标值和下标的关系

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        records = dict()
        for index, value in enumerate(nums):
            if target - value in records:
                return [records[target- value], index]
            records[value] = index
        return []
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值