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
705. 设计哈希集合
不符合要求的做法:
class MyHashSet:
def __init__(self):
self.hashset = set()
def add(self, key: int) -> None:
self.hashset.add(key)
def remove(self, key: int) -> None:
if key in self.hashset:
self.hashset.remove(key)
def contains(self, key: int) -> bool:
if key in self.hashset:
return True
return False
规范题解见:详解 HashSet 的设计:在时间和空间上做权衡
706. 设计哈希映射
不符合要求的做法:
class MyHashMap:
def __init__(self):
self.hashmap = dict()
def put(self, key: int, value: int) -> None:
self.hashmap[key] = value
def get(self, key: int) -> int:
if key in self.hashmap:
return self.hashmap[key]
return -1
def remove(self, key: int) -> None:
if key in self.hashmap:
del self.hashmap[key]
规范题解见:详解 HashMap 的设计:在时间和空间上做权衡