当我们遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希法
几个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