【Leetcode】18、四数之和

给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复 的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):

  • 0 <= a, b, c, d < n
  • abcd 互不相同
  • nums[a] + nums[b] + nums[c] + nums[d] == target

你可以按 任意顺序 返回答案 。

示例 1:

复制代码
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

示例 2:

复制代码
输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]
python 复制代码
class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums.sort()
        n = len(nums)
        if not nums or n < 3:
            return []
        
        res = []
        for i in range(n):
            # 如果第一个值大于零,直接返回空
            if nums[i] > 0 and nums[i]>target and target>0:
                break
            # 如果当前值等于上一个值,跳过,进入下一次循环,去除重复值
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            
            for j in range(i+1,n):
                if nums[i] + nums[j] > target and target>0:
                    break
                if j > i+1 and nums[j] == nums[j-1]:
                    continue
                L = j + 1
                R = n - 1
                while (L < R): # 如果 L>R 或者 L=R 就结束
                    if nums[i] + nums[j] + nums[L] + nums[R] == target:
                        res.append([nums[i],nums[j], nums[L], nums[R]])
                        while L < R and nums[L] == nums[L + 1]:
                            L = L + 1
                        while L < R and nums[R] == nums[R - 1]:
                            R = R - 1
                        L = L + 1
                        R = R - 1
                    # 如果三数之和大于零,就将R--
                    elif nums[i] + nums[j] + nums[L] + nums[R] > target:
                        R = R - 1
                    else:
                        L = L + 1
        return res
相关推荐
Han.miracle16 分钟前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8242 小时前
前后缀分解
算法
你好,我叫C小白3 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林5 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway5 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No76 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区6 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫6 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
liu****6 小时前
8.list的模拟实现
linux·数据结构·c++·算法·list
地平线开发者7 小时前
征程 6 | 征程 6 工具链如何支持 Matmul/Conv 双 int16 输入量化?
算法·自动驾驶