18. 四数之和
题目
给你一个由 n
个整数组成的数组 nums
,和一个目标值 target
。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]]
(若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a
、b
、c
和d
互不相同nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:
输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]
提示:
1 <= nums.length <= 200
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
解答
思路
代码
Python 代码
python
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
ans = []
n = len(nums)
for a in range(n - 3):
x = nums[a]
if a > 0 and x == nums[a - 1]:
continue
if x + nums[a + 1] + nums[a + 2] + nums[a + 3] > target:
break
if x + nums[-3] + nums[-2] + nums[-1] < target:
continue
for b in range(a + 1, n - 2):
y = nums[b]
if b > a + 1 and y == nums[b - 1]:
continue
if x + y + nums[b + 1] + nums[b + 2] > target:
break
if x + y + nums[-2] + nums[-1] < target:
continue
c = b + 1
d = n - 1
while c < d:
s = x + y + nums[c] + nums[d]
if s > target:
d -= 1
while c < d and nums[d] == nums[d + 1]:
d -= 1
elif s < target:
c += 1
while c < d and nums[c] == nums[c - 1]:
c += 1
else:
ans.append([x, y, nums[c], nums[d]])
d -= 1
while c < d and nums[d] == nums[d + 1]:
d -= 1
c += 1
while c < d and nums[c] == nums[c - 1]:
c += 1
return ans