LeetCode 18. 4Sum (求和4)

原题

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.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

Reference solution

分析

这里直接提供一个 N 个数相加为 target 的通用模板,再代入 N = 4;

  • 首先先排序
  • 然后用K - 2个指针做O(N^(K - 2))的遍历
  • 剩下2个指针从第2步的剩余区间里面找,找的方式是使用两个指针p, q分别指向剩余区间的首尾,判断两个指针的和与target - 第2步的和的关系,对应的移动指针。即如果两个数的和大了,那么,q–;如果两个数的和小了,那么,p++;等于的话,输出结果。要时刻注意p < q.
  • 用p,q查找剩余区间结束之后,需要移动前面的K-2个值,这里需要在移动的过程中做个去重,找到和前面不同的值继续查找剩余区间。

时间复杂度是O(N^3),空间复杂度是O(1).

Python Version

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        if len(nums) < 4:
            return []
        
        nums.sort()
        res = []
        temp = []
        self.NSum(nums, target, 4, temp, res)
        return res
    
        
    def NSum(self, nums, target, N, temp, res):
        if len(nums) < N or target < nums[0] * N or target > nums[-1] * N:
            return 
        if N == 2:
            left = 0
            right = len(nums) - 1
            while left < right:
                if nums[left] + nums[right] < target:
                    left += 1
                elif nums[left] + nums[right] > target:
                    right -= 1
                else:
                    res.append(temp + [nums[left], nums[right]])
                    left += 1
                    right -= 1
                    while left < right and nums[left] == nums[left - 1]:
                        left += 1
                    while left < right and nums[right] == nums[right + 1]:
                        right -= 1
        else:
            for i in range(len(nums) - N + 1):
                if i > 0 and nums[i] == nums[i-1]:
                    continue
                self.NSum(nums[i+1:], target - nums[i], N - 1, temp + [nums[i]], res)
                

再提供一个普通版,直接针对 4sum 的求解方案;

Python Version

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        if len(nums) < 4:
            return []
        
        nums.sort()
        res = []
        temp = []
        # self.NSum(nums, target, 4, temp, res)
        for i in range(len(nums) - 3):
            for j in range(i+1, len(nums) - 2):   
                base = target - nums[i] - nums[j]
                left = j + 1
                right = len(nums) - 1
                while left < right:
                    if nums[left] + nums[right] < base:
                        left += 1
                    elif nums[left] + nums[right] > base:
                        right -= 1
                    else:
                        if [nums[i], nums[j], nums[left], nums[right]] not in res:
                            res.append([nums[i], nums[j], nums[left], nums[right]])
                        left += 1
                        right -= 1

        return res

        

Note:

  1. 这里因为先对列表进行了排序,所以后面判断是否重复的时候可以直接采用 if [nums[i], nums[j], nums[left], nums[right]] not in res:,因为 i < j < left < right,而列表已排序,所以可以保证相同结果对应相同 [[nums[i], nums[j], nums[left], nums[right]]:,可据此性质进行去重。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值