18. 四数之和

作者: 不爱去冒险的少年y | 来源:发表于2018-05-18 17:27 被阅读0次

18. 四数之和

给定一个包含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]

]

class Solution:

    def fourSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[List[int]]

        """

        res, dicti = set(), {}

        numLen = len(nums)

        nums.sort()

        for i in range(numLen):

            for j in range(i+1, numLen):

                key = nums[i] + nums[j]

                if key not in dicti.keys():

                    dicti[key] = [(i,j)]

                else:

                    dicti[key].append((i,j))

        for i in range(numLen):

            for j in range(i+1, numLen-2):

                exp = target - nums[i] -nums[j]

                if exp in dicti.keys():

                    for tmpIndex in dicti[exp]:

                        if tmpIndex[0] > j:

                            res.add((nums[i], nums[j], nums[tmpIndex[0]], nums[tmpIndex[1]]))

        return [list(i) for i in res]

相关文章

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

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

  • LeetCode-18 四数之和

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

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

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

  • 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.四数之和

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

  • 18. 四数之和

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

  • 18.四数之和

    自己解法 四数之和解题思路和三数之和类似,不过这个方式是固定前两个数字,后面两个数字用夹逼的方式向中间逼近,这样时...

网友评论

    本文标题:18. 四数之和

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