【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
相关推荐
全栈凯哥17 分钟前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥20 分钟前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu24 分钟前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
Humbunklung41 分钟前
机器学习算法分类
算法·机器学习·分类
Ai多利1 小时前
深度学习登上Nature子刊!特征选择创新思路
人工智能·算法·计算机视觉·多模态·特征选择
蒟蒻小袁1 小时前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先
Q8137574602 小时前
中阳视角下的资产配置趋势分析与算法支持
算法
yvestine2 小时前
自然语言处理——文本表示
人工智能·python·算法·自然语言处理·文本表示
GalaxyPokemon2 小时前
LeetCode - 148. 排序链表
linux·算法·leetcode
iceslime3 小时前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析