描述
给定一个包含 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]
]
分析
排序
可以拆成两个两数求和
用set来去掉重复
i从0-len-2遍历,j从i+1到len-1遍历,可以得到所有可能的两数之和
用python的字典存储,将key存储为两数之和,对应的值为遍历所对应的(i,j)
这样词典newlist里就装着所有前两个数的和以及组成当前和的所有对应下标元组
接着找剩下的两个数
仍然是两层循环(p,q),只不过从第三个数开始遍历,
每次判断target - (nums[p]+nums[q])是否在上面的词典里
在的话,在判断对应的所有可能(i,j)里,这个j是不是比p小,小的话说明是前面的两个数,不会出现重复的问题,然后将元祖添加到set里
最后在转化为数组
代码
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
newnums = {}
length = len(nums)
List = set()
if length < 4:
return []
if length == 4:
if nums[0]+nums[1]+nums[2]+nums[3] == target:
return [nums]
else : return []
nums= sorted(nums)
for i in range(0,length-1):
for j in range(i+1,length):
key = nums[i]+nums[j]
if key in newnums:
newnums[key].append((i,j))
else:
newnums[key] = [(i,j)]
for p in range(2,length-1):
for q in range(p+1,length):
t = target - (nums[p]+nums[q])
if t in newnums:
for index in newnums[t]:
if index[1]<p:
List.add((nums[index[0]],nums[index[1]],nums[p],nums[q]))
return [list(li) for li in List]