454.四数相加II
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hash = dict()
for i in nums1:
for j in nums2:
if i + j in hash:
hash[i+j] += 1
else:
hash[i+j] = 1
count = 0
for i in nums3:
for j in nums4:
if (-i-j) in hash:
count += hash[-i-j]
return count
注意count的计算方式。
将四个数组分成两组。首先计算A[i]+B[j]的值并存入哈希映射中。key为A[i]+B[j],value为A[i]+B[j]出现的次数。
C[i]+D[j]。如果-(C[i]+D[j])出现在哈希映射中,那么将-(C[i]+D[j])对应的值累加到答案中。
set(集合)只有key
map(映射)有key和value
383.赎金信
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
hash = [0] * 26
for i in magazine:
hash[ord(i) - ord('a')] += 1
for i in ransomNote:
if hash[ord(i) - ord('a')] == 0:
return False
else:
hash[ord(i) - ord('a')] -= 1
return True
和242. 有效的字母异位词 - 力扣(LeetCode)类似,都是采用数组的方式来求
用一个长度为26的数组还记录magazine里字母出现的次数。
然后再用ransomNote去验证这个数组是否包含了ransomNote所需要的所有字母。
15.三数之和
双指针
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
ans = []
n = len(nums)
nums.sort()
for i in range(n):
# 如果排序后第一个数>0, 直接结束
if nums[i] > 0:
break
left = i + 1
right = n - 1
# 去重a
if i >= 1 and nums[i] == nums[i-1]:
continue # continue不执行后续代码,直接进入下一次循环
while left < right:
sum = nums[i] + nums[left] + nums[right]
if sum > 0:
right -= 1
elif sum < 0 :
left += 1
else:
ans.append([nums[i], nums[left], nums[right]])
# 去重b和c
while left < right and nums[right] == nums[right -1]:
right -= 1
while left < right and nums[left] == nums[left + 1]:
left += 1
left += 1
right -= 1
return ans
去重逻辑第一次接触,好难