454.四数相加II
题目链接/文章讲解/视频讲解:代码随想录
方法:先遍历前两个列表,计算元素和,作为字典的key,value表示该和出现的次数,再遍历后两个列表,判断0-(后两个列表的元素和)是否在字典内,若在,则最终返回值加value
class Solution(object):
def fourSumCount(self, nums1, nums2, nums3, nums4):
# 使用字典存储nums1和nums2中的元素及其和
hashmap = dict()
for n1 in nums1:
for n2 in nums2:
if n1 + n2 in hashmap:
hashmap[n1+n2] += 1
else:
hashmap[n1+n2] = 1
# 如果 -(n1+n2) 存在于nums3和nums4, 存入结果
count = 0
for n3 in nums3:
for n4 in nums4:
key = - n3 - n4
if key in hashmap:
count += hashmap[key]
return count
15. 三数之和
题目链接/文章讲解/视频讲解:代码随想录
方法:双指针法(先保证单调性)+元素去重
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
n = len(nums)
for i in range(len(nums)):
if nums[i] > 0:
return res
left = i + 1
right = n - 1
#第一个元素去重
if i > 0 and nums[i] == nums[i-1]:
continue
while left < right:
if nums[i] + nums[left] + nums[right] > 0:
right -= 1
elif nums[i] + nums[left] + nums[right] < 0:
left += 1
else:
res.append([nums[i],nums[left],nums[right]])
#第2和第3个元素去重
while right > left and nums[left] == nums[left+1]:
left += 1
while right > left and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
return res
18 四数之和
题目链接/文章讲解/视频讲解:代码随想录
方法:三数之和的基础上,嵌套一个for循环,关键在剪枝和去重
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
res = []
for i in range(len(nums)-1):
#剪枝
if nums[i] > target and nums[i] > 0:
return res
#去重
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1,len(nums)):
#剪枝
if nums[i] + nums[j] > target and target > 0:
break
#去重
if j > i+1 and nums[j] == nums[j-1]:
continue
left = j + 1
right = len(nums) -1
while left < right:
tmp = nums[i] + nums[j] + nums[left] + nums[right]
if tmp > target:
right -= 1
elif tmp < target:
left += 1
else:
res.append([nums[i],nums[j],nums[left],nums[right]])
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 res