码迷,mamicode.com
首页 > 编程语言 > 详细

力扣 ——4Sum (四数之和)python 实现

时间:2019-09-20 21:25:37      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:targe   pen   target   continue   list   题目   type   for   bsp   

题目描述:

中文:

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

英文:

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums = sorted(nums)
        res = []

        if not nums or len(nums) < 4:
            return res

        if nums[0] + nums[1] + nums[2] + nums[3] > target:
            return res

        if nums[-1] + nums[-2] + nums[-3] + nums[-4] < target:
            return res

        for i in range(0, len(nums)):
            if nums[i] + nums[-1] + nums[-2] + nums[-3] < target:
                continue
            for j in range(i + 1, len(nums) - 2):
                if nums[i] + nums[j] + nums[-2] + nums[-1] < target:
                    continue
                x = j + 1
                y = len(nums) - 1
                while x < y:
                    if nums[i] + nums[j] + nums[x] + nums[y] == target:
                        res.append([nums[i], nums[j], nums[x], nums[y]])
                        x = x + 1
                        while x < y and nums[x] == nums[x - 1]:
                            x = x + 1
                    elif nums[i] + nums[j] + nums[x] + nums[y] < target:
                        x = x + 1
                    else:
                        y = y - 1

        rr = []
        for r in res:
            if r not in rr:
                rr.append(r)
        return rr

 

题目来源:力扣题库

力扣 ——4Sum (四数之和)python 实现

标签:targe   pen   target   continue   list   题目   type   for   bsp   

原文地址:https://www.cnblogs.com/spp666/p/11559534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!