减少不必要的计算,双指针可以将复杂度降低一个数量级。
454. 四数相加 II
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
sumDict12 = dict()
sumDict34 = dict()
for num1 in nums1:
for num2 in nums2:
sum_temp = num1 + num2
if sum_temp not in sumDict12:
sumDict12[sum_temp] = 1
else:
sumDict12[sum_temp] += 1
for num3 in nums3:
for num4 in nums4:
sum_temp = num3 + num4
if sum_temp not in sumDict34:
sumDict34[sum_temp] = 1
else:
sumDict34[sum_temp] += 1
res = 0
for key, value in sumDict12.items():
temp = 0-key
if temp in sumDict34:
res += value * sumDict34[temp]
return res
383. 赎金信
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
charDict = dict()
for char in magazine:
if char not in charDict:
charDict[char] = 1
else:
charDict[char] += 1
for char in ransomNote:
if char not in charDict:
return False
if charDict[char] == 0:
return False
charDict[char] -= 1
return True
15. 三数之和
- 一开始用了暴力求解,提交后发现超时,然后才想起排序后的特点。sum<target的时候,小的数字需要增加,反之大的数字需要减小。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# 先排序
nums.sort()
res = []
i = 0
length = len(nums)
while i < length -2:
j = i + 1
k = length - 1
while j < k:
# print(i,j,k)
temp = nums[i] + nums[j] + nums[k]
if temp == 0:
res.append([nums[i], nums[j], nums[k]])
k -= 1
while j < k and nums[k] == nums[k+1]:
k -= 1
j += 1
while j < k and nums[j] == nums[j-1]:
j += 1
elif temp > 0:
k -= 1
while j < k and nums[k] == nums[k+1]:
k -= 1
else:
j += 1
while j < k and nums[j] == nums[j-1]:
j += 1
i += 1
while i < length - 2 and nums[i] == nums[i-1]:
i += 1
return res
# 下面是一个暴力求解
# while i < length - 2:
# j = i + 1
# while j < length - 1:
# k = j + 1
# while k < length:
# if nums[i] + nums[j] + nums[k] == 0:
# res.append([nums[i], nums[j], nums[k]])
# if nums[i] + nums[j] + nums[k] > 0:
# break
# # print(i,j,k)
# k += 1
# while k < length and nums[k] == nums[k-1]:
# k += 1
# j += 1
# while j < length -1 and nums[j] == nums[j-1]:
# j += 1
# i += 1
# while i < length -2 and nums[i] == nums[i-1]:
# i += 1
# return res
18. 四数之和
- 与三数之和是一样的,就是最外层再多一个循环
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
length = len(nums)
i = 0
res = []
while i < length-3:
j = i + 1
while j < length - 2:
left = j + 1
right = length - 1
while left < right:
temp = nums[i] + nums[j] + nums[left] + nums[right]
if temp == target:
res.append([nums[i], nums[j], nums[left],nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif temp > target:
right -= 1
else:
left += 1
j += 1
while j < length - 2 and nums[j] == nums[j-1]:
j += 1
i += 1
while i < length -3 and nums[i] == nums[i-1]:
i += 1
return res