Leetcode 18.四数之和(4Sum)

一个人想着一个人 提交于 2020-01-30 13:22:56

Leetcode 18.四数之和

1 题目描述(Leetcode题目链接

  给定一个包含 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]
]

2 题解

  题目和三数之和很像,在三数之和的外面再套一层循环,并增加一些判断就可以了。

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        length = len(nums)
        retv = []
        for n in range(length - 3):
			if nums[n] + nums[n + 1] + nums[n + 2] + nums[n + 3] > target: # 如果当下四个数之和大于target,则之后的全大于target,直接返回结果
                return retv
            if n > 0 and nums[n] == nums[n - 1]: # 如果固定的数和上一个重复,直接 略过
                continue
            if nums[n] + nums[-1] + nums[-2] + nums[-3] < target: # 如果当前固定的数和后三个最大的数之和小于target则这层都小于target,略过
                continue
            comp = target - nums[n] # 转化为3数之和的target
            
            for i in range(n+1, length - 2):
                if i > n + 1 and nums[i] == nums[i-1]: #同三数之和的判断
                    continue
                if nums[i] + nums[i + 1] + nums[i + 2] > comp: #同三数之和的判断
                    continue
                if nums[i] + nums[-1] + nums[-2] < comp: #同三数之和的判断
                    continue
                left, right = i + 1, length - 1
                while left < right:
                    x = nums[i] + nums[left] + nums[right]
                    if x == comp:
                        retv.append([nums[n], nums[i], 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 x > comp:
                        right -= 1
                    else:
                        left += 1
        return retv
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!