Leetcode 18. 四数之和
题目说明
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
题目解析
-
双指针法
两层遍历,对剩下的元素建立左右指针。比较遍历元素与左右指针之和是否与target相等。若相等,加入结果列表。
-
剪枝
遍历的第一层,若前四个元素之和大于target,break
遍历的第一层,若遍历的元素和列表最后3个元素之和小于target,continue
遍历的第一层,若与之前元素相等,continue
遍历的第二层,若确定的第一层元素与第二层的前3个元素之和大于target,break
遍历的第二层,若确定的第一层元素与第二层元素与列表最后2个元素之和小于target,continue
遍历的第二层,若与之前元素相等,continue -
时间复杂度 O( n 3 n^3 n3), 空间复杂度 O(1)
Python代码
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums = sorted(nums)
result = []
for i in range(len(nums) - 3):
if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target:
break
if nums[i] + nums[len(nums) - 1] + nums[len(nums) - 2] + nums[len(nums) - 3] < target:
continue
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, len(nums) - 2):
if nums[j] + nums[i] + nums[j + 1] + nums[j + 2] > target:
break
if nums[j] + nums[i] + nums[len(nums) - 1] + nums[len(nums) - 2] < target:
continue
if j > i + 1 and nums[j] == nums[j - 1]:
continue
l, r = j + 1, len(nums) - 1
while l < r:
mid_result = nums[i] + nums[j] + nums[l] + nums[r]
if mid_result == target:
result.append([nums[i], nums[j], nums[l], nums[r]])
while l + 1 < r and nums[l] == nums[l + 1]:
l += 1
while l + 1 < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
r -= 1
elif mid_result < target:
l += 1
else:
r -= 1
return result