Leetcode_18【四数之和】

时间:2019-12-12 11:45:43   收藏:0   阅读:133

文章目录:


题目:

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


 

脚本一:【用时1330ms】

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        num1 = len(nums)
        nums.sort()
        res = []
        for i in range(num1-3):
            if nums[i] > target and nums[i] > 0:
                return(res)
            if i > 0 and nums[i] == nums[i-1]:
                continue
            for j in range(i+1,num1-2):
                if j > i+1 and nums[j] == nums[j-1]:
                    continue
                k,l = j+1,num1-1
                while k < l:
                    s = nums[i] + nums[j] + nums[k] + nums[l]
                    if s < target:
                        k = k+1
                        while k < l and nums[k] == nums[k - 1]: k += 1
                    elif s > target:
                        l -= 1
                        while k < l and nums[l] == nums[l + 1]: l -= 1
                    else:
                        res.append([nums[i],nums[j],nums[k],nums[l]])
                        k += 1
                        l -= 1
                        while k < l and nums[k] == nums[k - 1]: k += 1
                        while k < l and nums[l] == nums[l + 1]: l -= 1
        return(res)

 


 

脚本一逻辑:


 

脚本二:【用时:80ms】【转载】

class Solution(object):
    def fourSum(self, nums, target):
        def findNsum(l, r, target, N, result, results):
            if r - l + 1 < N or N < 2 or target < nums[l] * N or target > nums[r] * N:
                return
                
            # two pointers solve sorted 2-sum problem
            if N == 2:
                while l < r:
                    s = nums[l] + nums[r]
                    if s == target:
                        results.append(result + [nums[l], nums[r]])
                        l += 1
                        while l < r and nums[l] == nums[l - 1]:
                            l += 1
                    elif s < target:
                        l += 1
                    else:
                        r -= 1
            else:
                for i in range(l, r + 1):
                    if i == l or (i > l and nums[i - 1] != nums[i]):
                        findNsum(i + 1, r, target - nums[i], N - 1, result + [nums[i]], results)
        nums.sort()
        results = []
        findNsum(0, len(nums) - 1, target, 4, [], results)
        return results

脚本二逻辑:

原文:https://www.cnblogs.com/mailong/p/12026507.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!