题目
给定一个包含 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]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
和三数之和,最接近的三数之和差不多,a+b+c+d=target,我们先算出a+b再用双指针去找c+d使a+b+c+d=target。
代码
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
li=sorted(nums)
l=len(li)
ans=[]
for i in range(l):
if i!=0 and li[i]==li[i-1]:
continue
for j in range(i+1,l):
if j!=i+1 and li[j]==li[j-1]:
continue
x=j+1
y=l-1
while(x<y):
#print(x,y,li[x],li[y],li[i])
if x !=j+1 and li[x]==li[x-1]:
x=x+1
continue
if y!=l-1 and li[y]==li[y+1]:
y=y-1
continue
if li[x]+li[y]+li[i]+li[j]==target:
ans.append([li[i],li[j],li[x],li[y]])
x=x+1
y=y-1
else:
if li[x]+li[y]+li[i]+li[j]>target:
y=y-1
else:
x=x+1
return ans