LeetCode 18.四数之和 Python

题目描述:


思路解析:

首先计算 nums[a] 和 nums[b] 两数之和,再利用 c、d 双指针分别进行查找,此时类似于三数之和。

四数之和与三数之和的不同之处在于:三数之和中给定了目标值为 0,而四数之和中目标值随机。

如果对 nums[a] 的判断条件仍为 nums[a] > target,则会漏掉一部分结果,举个栗子:

若数组为[- 5, - 3, - 1, - 1, 2, 3, 6],给定 target = - 6,a 对应的数值为 -5 时,nums[a] > target,但显然还应该继续向后搜索,所以这是四数之和与三数之和不同之处。

注:结果中不可以包含重复的四元组。

所以只有 a 和 b 的值可以重复,c 和 d的值不可以重复。


代码:

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        result = []
        n = len(nums)
        nums.sort()
        for a in range(n-2):  # for a in range(n):√
            # if (nums[a] + nums[a+1] + nums[a+2] + nums[a+3])>target:索引超出范围
            if nums[a] > 0 and target < 0:   # if nums[a] > target:输出结果有问题
                break
            if a>0 and nums[a] == nums[a-1]:
                continue
            for b in range(a+1, n):
                if b>a+1 and nums[b] == nums[b-1]:
                    continue
                two_sum = nums[a] + nums[b]
                if two_sum > 0 and target < 0:  # if two_sum > target:报错
                    break
                c,d = b+1, n-1
                while c < d:   
                    sum = two_sum + nums[c] + nums[d]
                    if sum == target:
                        result.append([nums[a], nums[b], nums[c], nums[d]])
                        c += 1
                        d -= 1
                        while c < d and nums[c] == nums[c-1]: 
                            c += 1
                        while c < d and nums[d] == nums[d+1]:
                            d -= 1
                    elif sum < target:
                        c += 1
                    else:
                        d -= 1
        return result
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值