198 - 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] ]

解答

排序,然后双指针,两层循环

递归

https://leetcode.com/problems/4sum/discuss/8545/Python-140ms-beats-100-and-works-for-N-sum-(Ngreater2)

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        results = []
        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
            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)
        findNsum(0, len(nums)-1, target, 4, [], results)
        return res

Runtime: 84 ms, faster than 92.68% of Python3 online submissions for 4Sum.

Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for 4Sum.

双指针

https://leetcode-cn.com/problems/4sum/solution/gu-ding-liang-ge-shu-yong-shuang-zhi-zhen-zhao-lin/

Runtime: 92 ms, faster than 86.42% of Python3 online submissions for 4Sum.

Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for 4Sum.

Last updated

Was this helpful?