代码随想录算法训练营第六天【哈希表】| 242, 349, 202, 1

当我们遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希法

几个hash:数组(数较少),set(数较多),map(有对应值)

python里的几个容器:

1. defaultdict

当字典里的key不存在但被查找时,返回的不是keyError而是一个默认值(list对应[ ],str对应的是空字符串,set对应set( ),int对应0)

2. Counter

>>> from collections import Counter

>>> c = Counter('abcasd')

>>> c

Counter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})

242. Valid Anagram

做过,此为数组法

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

349. Intersection of Two Arrays

return list(set(nums1) & set(nums2))

202. Happy Number

“题目中说了会 无限循环,那么也就是说求和的过程中,sum会重复出现,这对解题很重要。所以这道题目使用哈希法,来判断这个sum是否重复出现,如果重复了就是return false, 否则一直找到sum为1为止”

1. Two Sum

用dictionary

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        numMap = {} #build a dictionary for hashtable
        for i in range(len(nums)):
            complement = target - nums[i]
            if complement in numMap:
                return [numMap[complement],i] #return the two numbers' index
            numMap[nums[i]] = i #hashtable_index as number, hashtable_value as index
        return [] # no sol
        

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值