代码随想录算法训练营第六天| LeetCode242.有效的字母异位词 、LeetCode349. 两个数组的交集、LeetCode202. 快乐数、LeetCode1. 两数之和

哈希表

242.有效的字母异位词

题目描述: 242.有效的字母异位词.

解法

数组
class Solution(object):
    def isAnagram(self, s, t):
        c = [0] * 26
        for i in s:
            c[ord(i)-ord('a')] += 1
        for j in t:
            c[ord(j)-ord('a')] -= 1
        for k in range(26):
            if c[k] != 0:
                return False
        return True

数字转ASCII:chr()
ASCII转数字:ord()

默认字典
class Solution(object):
    def isAnagram(self, s, t):
        from collections import defaultdict
        dict_s = defaultdict(int)
        dict_t = defaultdict(int)
        for i in s:
            dict_s[i] += 1
        for j in t:
            dict_t[j] += 1
        return dict_s == dict_t

defaultdict是字典的一个子类,正常的字典当key不存在时会返回异常,但是defaultdict会给key一个默认的值,设定好类型即可,例如defaultdict(int)的每一个key的默认值就是0。

Counter
class Solution(object):
    def isAnagram(self, s, t):
        from collections import Counter
        dict_s = Counter(s)
        dict_t = Counter(t)
        return dict_s == dict_t

Counter也是一种字典,用于计数,计数可以是0或者负值,可以直接将list作为参数使用。

349. 两个数组的交集

题目描述: 349. 两个数组的交集.

解法

根据边界使用定长数组
class Solution(object):
    def intersection(self, nums1, nums2):
        list_1 = [0] * 1001
        list_2 = [0] * 1001
        inter = []
        for num in nums1:
            list_1[num] += 1
        for num in nums2:
            list_2[num] += 1
        for k in range(1001):
            if list_1[k] * list_2[k] >=1:
                inter.append(k)
        return inter
使用set
class Solution(object):
    def intersection(self, nums1, nums2):
        return list((set(nums1) & set(nums2)))

注意返回的是一个list,&表示求交集,用于集合之间的计算

使用set和dict
class Solution(object):
    def intersection(self, nums1, nums2):
        d = {}
        res = set()
        for num in nums1:
            d[num] = d.get(num,1) 
        for num in nums2:
            if num in d:
                res.add(num)
        return list(res)

先存到dict里,再进行查找,这是时间和内存都最佳的方案

202. 快乐数

题目描述: 202. 快乐数.

解法

class Solution(object):
    def isHappy(self, n):
        s = set()
        while n != 1:
            n = sum(int(i) ** 2 for i in str(n))
            if n in s:
                return False
            s.add(n)
        return True

今天的题目主要都是数组,集合,字典的应用,本质上没什么区别

1. 两数之和

题目描述: 1. 两数之和.

解法

class Solution(object):
    def twoSum(self, nums, target):
        d = dict()
        for i,num in enumerate(nums):
            if (target - num) in d:
                return [d[target-num],i]
            d[num] = i

abandon,没什么好说的

总结

哈希表在python中的实现主要通过set、dict、list实现,如果不需要找到索引位置,需要返回一个集合,可以使用set。如果有一定边界,可以使用定长的list。dict比较万能,但是不能限定长度,需要掌握get方法,.get(key,value),value可选,如果没有找到,返回固定值value

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值