leetcode学习:18.四数之和

该篇博客详细介绍了如何解决编程题中的四数之和问题。通过排序、双指针等算法,有效地找到数组中四个数的组合,使得它们的和等于目标值。文章提供了具体的Python代码实现,并展示了示例输入和输出。尽管执行效率不高,但能够正确找出所有不重复的四元组。
摘要由CSDN通过智能技术生成

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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值