四数之和
1,程序简介
-
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + 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 = [], target = 0
- 输出:[]
提示:
- 0 < = n u m s . l e n g t h < = 200 0 <= nums.length <= 200 0<=nums.length<=200
- − 1 0 9 < = n u m s [ i ] < = 1 0 9 -10^9 <= nums[i] <= 10^9 −109<=nums[i]<=109
- − 1 0 9 < = t a r g e t < = 1 0 9 -10^9 <= target <= 10^9 −109<=target<=109
2,程序代码
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 13 21:38:56 2022
Function: 四数之和
@author: 小梁aixj
"""
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
results = []
N = len(nums)
i = 0
while i < N-3:
if i > 0 and nums[i] == nums[i-1]:
i += 1
continue
j = i+1
while j < N-2:
if j > i+1 and nums[j] == nums[j-1]:
j += 1
continue
k = j+1
l = N-1
while k < l:
if k > j+1 and nums[k] == nums[k-1]:
k += 1
continue
while k < l and (target - nums[i] - nums[j] - nums[k] - nums[l]) < 0:
l -= 1
if k >= l:
break
if target == nums[i] + nums[j] + nums[k] + nums[l]:
results.append([
nums[i],
nums[j],
nums[k],
nums[l]
])
k += 1
j += 1
i += 1
return results
# %%
s = Solution()
print(s.fourSum(nums = [1,0,-1,0,-2,2], target = 0))