18.四数之和

18. 四数之和

方法一:排序+双指针

思想:与三数之和相同

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        n = len(nums)
        ret = list()
        if n < 4:#如果数组长度小于4个,则没有四数之和
            return ret
        nums.sort() #对数组进行排序
        l = len(nums)
        for i in range(l - 3):
            if i > 0 and nums[i] == nums[i - 1]: #去除i位置相同的元素
                continue
            if nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target:#左边的四位数之和大于target,表示右边的数之和始终大于target,不存在四树枝和等于target
                break
            if nums[i] + nums[l-1] + nums[l-2] + nums[l-3] < target:#表示第一个数为nums[i],与数组中最大的三个数之和都小于target,则数组中肯定不存在nums[i]
                continue
            for j in range(i + 1, l - 2):
                if j > i + 1 and nums[j] == nums[j - 1]:
                    continue
                if nums[i] + nums[j] + nums[j+1] + nums[i+2] > target:
                    break
                if nums[i] + nums[j] + nums[l-1] + nums[l-2] < target:
                    continue
                left = j + 1
                right = l -1
                while left < right:
                    sum1 = nums[i] + nums[j] + nums[left] + nums[right]
                    if sum1 == target:
                        ret.append([nums[i], nums[j], 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
                    elif sum1 < target:
                        left += 1
                    else:
                        right -= 1
        return ret      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值