leetcode(26)哈希表系列题目
作者:互联网
242. 有效的字母异位词
哈希表方法,可适应更大规模字符集
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
dict_ = {}
for ch in s:
if ch in dict_:
dict_[ch] += 1
else:
dict_[ch] = 1
for ch in t:
if ch in dict_:
dict_[ch] -= 1
else:
dict_[ch] = 1
for v in dict_.values():
if v != 0:
return False
return True
或者取巧用Counter()函数
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
dict_s, dict_t = Counter(s), Counter(t)
if dict_s == dict_t:
return True
else:
return False
349. 两个数组的交集
注意:if hash.get(n):如果键n对应的值为0则返回False;而if n in hash:会返回True
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = []
hash = {}
for n in nums1:
if n not in hash:
hash[n] = 1
for n in nums2:
# if n in hash:
if hash.get(n):
hash[n] = 0
res.append(n)
return res
取巧的做法:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = []
set1, set2 = set(nums1), set(nums2)
for num in set1:
if num in set2:
res.append(num)
return res
1. 两数之和
用枚举更方便,就不需要通过索引再去取当前位置的值
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
records = dict()
for idx, val in enumerate(nums):
if target - val in records:
return [records[target - val], idx]
else:
records[val] = idx
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict_ = {}
for i in range(len(nums)):
if target - nums[i] in dict_:
return [dict_[target - nums[i]], i]
else:
dict_[nums[i]] = i
454. 四数相加 II
把num1和num2看作一个整体,num3和num4看作一个整体
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
res = 0
records = dict()
for i in nums1:
for j in nums2:
if i + j not in records:
records[i + j] = 1
else:
records[i + j] += 1
for i in nums3:
for j in nums4:
if -(i + j) in records:
res += records[-(i + j)]
return res
383. 赎金信
Counter()函数可以直接相减
若ransomNote中的字符在magazine没有出现则会返回Counter({'a': 1})
否则返回Counter(),即为空的
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
if len(ransomNote) > len(magazine):
return False
return not Counter(ransomNote) - Counter(magazine)
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
recordsR, recordsM = Counter(ransomNote), Counter(magazine)
for s in recordsR:
if recordsR[s] > recordsM[s]:
return False
return True
标签:26,return,int,Counter,List,records,dict,哈希,leetcode 来源: https://www.cnblogs.com/ttyangY77/p/16352966.html