【四数之和】python,排序+双指针

四层循环?(doge)

和【三数之和】题目很类似 

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        #a,b,c,d四个数,先固定两个数,那就是双指针问题了,令b=a+1,c=b+1,d=n-1
        ans=[]
        n=len(nums)
        #留3个位置啦,a
        for a in range(n-3):
            x=nums[a]
            #和三数之和那里一样,剪枝剪掉重复的
            if a>0 and x==nums[a-1]:
                continue
            #最小都大,可剪枝,后面肯定更大,所以可以退出了
            if x+nums[a+1]+nums[a+2]+nums[a+3]>target:
                break
            #最大都小,可剪枝,换个a
            if x+nums[-3]+nums[-2]+nums[-1]<target:
                continue
          #第二个数b
            for b in range(a+1,n-2):
                y=nums[b]
                #同样要跳过重复数字
                if b>a+1 and y==nums[b-1]:
                   continue
                #最小都大,打包退出了
                if x+y+nums[b+1]+nums[b+2]>target:
                   break
                #最大都小,换个b
                if x+y+nums[-2]+nums[-1]<target:
                   continue
                #然后可以开始双指针了
                c=b+1
                d=n-1
                while c<d:
                   sum=x+y+nums[c]+nums[d]
                   if sum>target:
                       d-=1
                       #相同的话结果也一样
                       while c<d and nums[d]==nums[d+1]:
                          d-=1
                   elif sum<target:
                       c+=1
                       #一样
                       while c<d and nums[c]==nums[c-1]:
                          c+=1
                   else:
                       ans.append([x,y,nums[c],nums[d]])
                       c += 1
                       #重复数字跳过
                       while c < d and nums[c] == nums[c - 1]:  
                          c += 1
                       d -= 1
                       while d > c and nums[d] == nums[d + 1]:  
                          d -= 1
        return ans

 

总结:

  1. 数组排序
  2. 四个数,我们可以设定2个数(a,b=a+1),两层循环
  3. c,d双指针(c=b+1,d逆序)
  4. 剪枝1:前4个数最小都大于target,后续肯定更大,break(a和b设定都要)
  5. 剪枝2:前+后共4数之和最大都比target小,只能跳过寻求更大的,continue(a和b设定都要)
  6. 剪枝3:重复数字跳过,和【三数之和】一样

  • 18
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值