【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
相关推荐
CV-Climber2 小时前
检索技术的实际应用
人工智能·算法
hhzz2 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_3 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI3 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅
atunet4 小时前
关于图算法中的连通分量检测与最小割问题7
算法
心运软件4 小时前
银行客户流失预测(Python 完整实战)
算法
邪神与厨二病4 小时前
牛客周赛 Round 153
python·算法
qizayaoshuap6 小时前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
皓月斯语7 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet7 小时前
树状结构在查询优化中的作用与实现细节7
算法