18.四数之和
题目描述
给定一个包含 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
输出:[]
思路
四数之和就是把第三个数字和第四个数字用双指针处理
算法
1.排序
2.遍历,用first标识
3.遍历,用second标识
4.third和fourth作双指针
5.返回结果
代码
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
length = len(nums)
if length<4:
return []
if length == 4:
if sum(nums) == target:
return [nums]
else:
return[]
li = []
nums.sort()
for first in range(length-3):
if first and nums[first] == nums[first-1]:
continue
for second in range(first+1,length-2):
if second>first+1 and nums[second] == nums[second-1]:
continue
third = second+1
fourth = length-1
while third<fourth:
##print(nums[first],nums[second],nums[third],nums[fourth])
if third>second+1 and nums[third]==nums[third-1]:
third +=1
continue
Sum = nums[first]+nums[second]+nums[third]+nums[fourth]
if Sum == target:
li.append([nums[first],nums[second],nums[third],nums[fourth]])
third+=1
elif Sum <target:
third +=1
else:
fourth-=1
return li
执行结果
执行用时:1364 ms, 在所有 Python3 提交中击败了19.66%的用户
内存消耗:14.8 MB, 在所有 Python3 提交中击败了92.13%的用户
题目来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。