代码随想录day5 哈希表

242. 有效的字母异位词 - 力扣(LeetCode)

遍历一次t和s,构成两个字典,遍历一遍字典,字典最多有26个键值对。时间O(n)空间O(1)。

python dict的get方法:dict_name.get(key, default_val_if_key_not_exist) -> dict_name[key]。

class Solution(object):
    def isAnagram(self, s, t):
        if len(s) != len(t):
            return False

        n = len(s)
        s_dict = dict()
        t_dict = dict()
        for i in range(n):
            s_dict[s[i]] = s_dict.get(s[i], 0) + 1
            t_dict[t[i]] = t_dict.get(t[i], 0) + 1
        
        for k, v in s_dict.items():
            try:
                flag = t_dict[k] == v
                if not flag:
                    return False
            except KeyError:
                return False
        
        return True

由于python的dict可以直接通过 == 判断两字典是否具有一致的键值对,可简化为: 

class Solution(object):
    def isAnagram(self, s, t):
        if len(s) != len(t):
            return False

        n = len(s)
        s_dict = dict()
        t_dict = dict()
        for i in range(n):
            s_dict[s[i]] = s_dict.get(s[i], 0) + 1
            t_dict[t[i]] = t_dict.get(t[i], 0) + 1

        return t_dict == s_dict

使用defaultdict可进一步化简:

python defaultdict vs dict: The difference is that a defaultdict will "default" a value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see if that key exists, and if it doesn't, set it to what you want.

from collections import defaultdict

class Solution(object):
    def isAnagram(self, s, t):
        if len(s) != len(t):
            return False

        n = len(s)
        s_dict = defaultdict(int)
        t_dict = defaultdict(int)
        for i in range(n):
            s_dict[s[i]] += 1
            t_dict[t[i]] += 1
            
        return t_dict == s_dict

349. 两个数组的交集 - 力扣(LeetCode)

使用三个集合set1、set2、res,遍历一次集合set1,时间O(n+m)空间O(n),其中m是集合和数组转换的耗时。

if num in set2耗时O(1):

In Python, sets are typically implemented using hash tables. Retrieving an element from a hash set (like Python's set) has an average time complexity of O(1).

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        set1 = set(nums1)
        set2 = set(nums2)
        res = set()
        for num in set1:
            if num in set2:
                res.add(num)
        
        return list(res)

202. 快乐数 - 力扣(LeetCode)

又记错python的整除... /是除,得到小数;//才是整除,得到整数。

时空复杂度都是O(logn)(如何证明?

class Solution:
    def isHappy(self, n: int) -> bool:
        visit = set()
        cur = n
        while cur not in visit:
            if cur == 1:
                return True

            visit.add(cur)
            s = 0 #sum
            while cur > 0:
                s += (cur % 10) ** 2
                cur //= 10 
            cur = s
        
        return False

1. 两数之和 - 力扣(LeetCode)

暴力解法,两层for循环,时间O(n^2)、空间O(1)。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        #暴力
        for i in range(len(nums) - 1):
            tar = target - nums[i]
            for j in range(i + 1, len(nums)):
                if nums[j] == tar:
                    return [i, j]

用哈希表,dict或defaultdict实现,记录已访问过的元素,令key为元素值、value为元素下标。只遍历一次数组,对当前元素cur,若哈希表里存在能够与cur加和为target的元素,返回;若不存在,将cur添加至哈希表,继续。时间和空间都为O(n)。由于题目要求返回下标,不可用集合set记录访问过的元素。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        #map,时间O(n)空间O(n)
        from collections import defaultdict
        visit = defaultdict()
        for i in range(len(nums)):
            try:
                idx = visit[target - nums[i]]
                return [i, idx]
            except KeyError:
                visit[nums[i]] = i

也可以不用try/except,直接判断 if key in dict_name,如下

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        #map,时间O(n)空间O(n)
        visit = dict()
        for i in range(len(nums)):
            com = target - nums[i] #complement
            if com in visit:
                return [i, visit[com]]
            else:
                visit[nums[i]] = i

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值