美文网首页
力扣每日一题:18.四数之和

力扣每日一题:18.四数之和

作者: 清风Python | 来源:发表于2021-05-08 00:47 被阅读0次

18.四数之和

https://leetcode-cn.com/problems/4sum/

难度:中等

题目:

给定一个包含n 个整数的数组nums和一个目标值target,判断nums中是否存在四个元素 a,b,c和 d,

使得a + b + c + d的值与target相等?找出所有满足条件且不重复的四元组。

注意:答案中不可以包含重复的四元组。

提示:

  • 0 <= nums.length <= 200
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9

示例:

示例 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
输出:[]

分析

如果之前做过 两数之和 ,
三数之和 ,
那么,这道题就是无脑多嵌套一层for循环了...

双层for循环判断num1和num2,然后使用双指针执行while循环,直到left == right截止。

解题:

class Solution:
    def fourSum(self, nums, target):
        nums.sort()
        ln = len(nums)
        ret = []
        if ln < 4:
            return []
        for i in range(0, ln - 3):
            num1 = nums[i]
            for j in range(i + 1, ln - 2):
                num2 = nums[j]
                left = j + 1
                right = ln - 1
                while left < right:
                    total = num1 + num2 + nums[left] + nums[right]
                    if total == target:
                        tmp = [num1, num2, nums[left], nums[right]]
                        if tmp not in ret:
                            ret.append(tmp)
                        right -= 1
                    elif total < target:
                        left += 1
                    else:
                        right -= 1
        return ret

欢迎关注我的公众号: 清风Python,带你每日学习Python算法刷题的同时,了解更多python小知识。

我的个人博客:https://qingfengpython.cn

力扣解题合集:https://github.com/BreezePython/AlgorithmMarkdown

相关文章

  • 力扣每日一题:18.四数之和

    18.四数之和 https://leetcode-cn.com/problems/4sum/[https://le...

  • 前端算法之哈字典&希表

    一、力扣01两数之和 二、力扣217存在重复元素 三、力扣349两个数组的交集 四、力扣1207独一无二的出现次数...

  • 【Leetcode算法题】18. 四数之和

    By Long Luo 18. 四数之和[https://leetcode-cn.com/problems/4su...

  • LeetCode-18 四数之和

    题目:18. 四数之和 难度:中等 分类:数组 解决方案:双指针 今天我们学习第18题四数之和,这是一道中等题。像...

  • 力扣每日一题:633.平方数之和

    633.平方数之和 https://leetcode-cn.com/problems/sum-of-square-...

  • ATRS第1周

    ATRS Algorithm算法题: 两数之和 - 力扣 (LeetCode) ``` function twoS...

  • 18.四数之和

    18.四数之和 题目链接:https://leetcode-cn.com/problems/4sum/[https...

  • 18. 四数之和

    一、题目原型: 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四...

  • 18. 四数之和

    知乎ID: 码蹄疾码蹄疾,毕业于哈尔滨工业大学。小米广告第三代广告引擎的设计者、开发者;负责小米应用商店、日历、开...

  • 18. 四数之和

    18.四数之和 给定一个包含n个整数的数组nums和一个目标值target,判断nums中是否存在四个元素a,b,...

网友评论

      本文标题:力扣每日一题:18.四数之和

      本文链接:https://www.haomeiwen.com/subject/mvuydltx.html