LeetCode 18: 4 Sum 寻找4数和

智能车竞赛轮腿穿越组:GPS+IMU导航绕桩实战技巧(附避坑指南) 本文详细介绍了智能车竞赛轮腿穿越组中GPS+IMU导航绕桩的实战技巧,包括硬件选型、传感器标定、路径规划及多传感器数据融合策略。通过实际案例和避坑指南,帮助参赛队伍提升导航精度和稳定性,避免常见错误。特别强调IMU安装位置和标定对导航系统的重要性。 阅读详情

链接


4Sum


难度


Medium


描述


Given an array nums of n integers and an integer target, are there elements a , b , c , and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

给定一个n个整数的数组n,和一个整数target,要求在数组当中找到所有四个数和等于targe的组合。返回所有不重复的组合。

注意:

The solution set must not contain duplicate quadruplets.

答案当中不能包含重复的组合

样例:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]


题解


这题是上周的3 Sum的进化版,要说这出题人也是够偷懒的,同样的题目稍微换一个条件就是新的题目了。要这样出题的话,我们分分钟可以出个十来题。


暴力


LeetCode当中的题目就没有几道是一次暴力无法解决的,如果有,就暴力两次。——承志。

显然,这题让我们寻找4个数的组合,满足它们的和等于target。这简直没有更明显的暴力暗示了,暗示我们可以暴力来解决,并且暴力的方法非常明确,暴力的代码非常简短。

我们直接跳过解释部分,来写下代码:

def 4Sum(array):
    n = len(array)
    ret = []
    for i in range(n):
        for j in range(i+1, n):
            for k in range(j+1, n):
                for l in range(k+1, n):
                    if array[i] + array[j] + array[k] + array[l] == target:
                        if [array[i], array[j], array[k], array[l]] not in ret:
                            ret.append([array[i], array[j], array[k], array[l]])
    return ret

显然,暴力法不是最好的,是最差的,不然也不用给大家写这篇文章了。

我们前面吐槽说这题和上周做的3 Sum题如出一辙,那么能否利用3 Sum的算法来完成4 Sum呢?毕竟这两题除了条件有细微的不同,大致题面完全相同。

如果我们真这么去想,又会有一个新的槽点:既然4 Sum可以用3 Sum来解决,然而我们又都知道3 Sum的解法之一是通过2 Sum,所以这不成了套娃问题了么?【狗头】


使用3 Sum


言归正传,回到算法本身,在3 Sum问题当中,我们通过two pointers算法,维护了一个区间,使得这个区间头尾元素的和等于一个特定值。所以我们利用3 Sum也一样,我们只需要枚举第一个元素,然后在剩下的数组当中,套用3 Sum寻找可能的组合即可。

解法也很简单,我们只需要把之前3 Sum的代码抄过来,然后增加一个调用函数即可。

class Solution:
    
    def three_sum(self, array, aim):
        # 无须排序,因为传入的时候已经有序了
        n = len(array)
        ret = []
        for i in range(n-2):
            # 判断第一个数是否重复
            if i > 0 and array[i] == array[i-1]:
                continue
            # 进行two pointers缩放
            j = i + 1
            k = n - 1
            target = aim - array[i]
            while j < k:
                cur_sum = array[j] + array[k]
                # 判断当前区间的结果和目标的大小
                if cur_sum < target:    
                    j += 1
                    continue
                elif cur_sum > target:
                    k -= 1
                    continue
                # 记录
                answer = [array[i], array[j], array[k]]
                ret.append(answer)
                # 继续缩放区间,寻找其他可能的答案
                j += 1
                while j < k and array[j] == array[j-1]:
                    j += 1
                k -= 1
                while j < k-1 and array[k] == array[k+1]:
                    k -= 1
        return ret
    
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        n = len(nums)
        # 对数组进行排序
        nums = sorted(nums)
        ret = []
        for i in range(n):
            # 枚举第一个元素重复的话需要跳过
            if i > 0 and nums[i] == nums[i-1]:
                continue
            # 获取3 Sum的结果
            # 由于3 Sum当中做了防止重复的判断,所以不需要判断重复
            sub_ret = self.three_sum(nums[i+1: ], target - nums[i])
            for subset in sub_ret:
                ret.append([nums[i]] + subset)
        return ret

双重two pointers


上面的算法固然可以,尤其是我们之前做了3 Sum的情况下,只要稍稍修改一点点,代码就可以投入使用了。但是这并不是最佳方案,我们来计算一下复杂度。

首先,我们枚举了第一个元素,它的复杂度是 O ( n ) O(n) O(n)。另外,3 Sum的复杂度是 O ( n 2 ) O(n^2) O(n2)。所以整体上,这是一个 O ( n 3 ) O(n^3) O(n3)的复杂度,虽然从问题层面来思考,要比 O ( n 4 ) O(n^4) O(n4)的暴力枚举提升了一个层次,但是看起来应该还有进化的空间。那么怎么进化呢?

一个想法是我们能不能跳过3 Sum直接用2 Sum?其实可以的,因为我们在3 Sum当中只枚举了第一个数,然后通过two pointers寻找剩下的两个数的组合。所以我们可以使用一次two pointers然后剩下的元素做2 Sum,但是仔细一想,既然我们已经用了一次two pointers了,为什么不做两次呢?虽然复杂度是一样的,但是可以减少map的使用。

想明白了,算法也就出来了。说白了就是套用两次two pointers。最外层的two pointers算法枚举两个数的和,中间的two pointers算法寻找剩下的两个数。

光凭脑子想可能还有些发蒙,我列出代码,我们结合代码一起看就清楚了。

class Solution:
    
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        n = len(nums)
        nums = sorted(nums)
        ret = []
        i, j = 0, n-1
        while i < j-2:
            while j > i+2:
                # two pointers算法
                l, r = i+1, j-1
                tar = target - nums[i] - nums[j]
                while l < r:
                    if nums[l] + nums[r] < tar:
                        l += 1
                    elif nums[l] + nums[r] > tar:
                        r -= 1
                    else:
                        ret.append([nums[i], nums[l], nums[r], nums[j]])
                        l += 1
                        r -= 1
                        # 跳过l和r的重复元素
                        while l < r and nums[l] == nums[l-1]:
                            l += 1
                        while l < r and nums[r] == nums[r+1]:
                            r -= 1
                # 跳过j的重复元素
                j -= 1
                while j > i+2 and nums[j] == nums[j+1]:
                    j -= 1
            # 对于新的i,j重新置为末尾
            j = n-1
            # 跳过i重复的元素
            i += 1
            while i+2 < j and nums[i] == nums[i-1]:
                i += 1
        return ret

我们结合代码来看,虽然我们使用了两套two pointers,但实际上,我们最外层并没有办法做到 O ( n ) O(n) O(n)的枚举。因为我们无法同时缩放两个区间,看起来是两个two pointers套用,但实际上还是只是用到了一个two pointers算法而已。我们最外层的遍历,相当于枚举了内层two pointers算法作用的区间。这个枚举是 O ( n 2 ) O(n^2) O(n2)的复杂度,整体的复杂度同样是 O ( n 3 ) O(n^3) O(n3)和使用3 Sum的一样。

但这不意味着我们讨论这种解法就没有意义了,相反,对于算法学习而言,比解出问题更重要的是对于问题充分的思考。虽然从表面上看我们费心想出来的另一种方案并没有得到提升,但是相比于提升而言,我们在此过程当中经历了充分的思考,无论是分析可行性还是最后分析复杂度,无比如此。正是在反复的思考当中,我们的算法思维才能养成,解题能力才能提升。

当然,另一个原因是不掰扯出一些道理来,这么大段话我就白写了。

今天的文章就到这里,如果觉得有所收获,请顺手扫码点个关注吧,你们的支持是我最大的动力。

鸿蒙5.0进阶开发:UI开发-不依赖UI组件的全局自定义弹出框 (openCustomDialog)(推荐) 本文介绍通过入参形式为ComponentContent创建自定义弹出框............ 阅读详情

相关推荐

别再手动量了!用Python+Open3D给BIM模型做‘CT扫描’,自动揪出施工误差(附完整代码)

本文介绍如何利用Python和Open3D技术实现BIM模型的毫米级施工误差自动检测。通过点云预处理、模型配准和偏差分析,系统能自动生成三维差异热力图和验收报告,显著提升施工质量检测效率。特别适合混凝土结构错位和钢结构安装偏差等常见问题的智能分析。

weixin_29284657的博客 248

分布式系统:向量时钟

在上一篇文章分布式系统:Lamport 逻辑时钟中我们知道Lamport 逻辑时钟帮助我们得到了分布式系统中的事件全序关系,但是对于同时发生的关系却不能很好的描述,导致无法描述事件的因果关系。向量时钟是在 Lamport 时间戳基础上演进的另一种逻辑时钟方法,它通过向量结构不但记录本节点的 Lamport 时间戳,同时也记录了其他节点的 Lamport 时间戳,因此能够很好描述同时发生关系以及事件...

weixin_33910385的博客 661

华为ENSP完整安装教程

华为ENSP完整安装教程

Hnm456756的博客 7425

向量时钟解决数据一致性

本文系转载,原文链接实在太长,请猛点这儿:。 向量时钟解决数据一致性 向量时钟简介 向量时钟,最早是用于分布式系统中进程间的时间同步。由于在分布式系统中没有一个直接的全局逻辑时钟。在一个由n个并发进程构成的系统中,每个事件的逻辑时钟均由一个n维向量(n元组)构成,其中第i维(分量)对应于第i个进程的逻辑时钟Vi 向

一见 1800

STM32——LCD—FSMC原理简介

STM32——LCD—FSMC原理简介

weixin_62584795的博客 2996

Steam崩溃:ntdll.dll报错0xc0000374...如何解决?

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断与性能调优」方法论,助你稳步进阶、放大技术价值。

**My Coding Family** 1192

算法6--SumK问题

整理总结一下与sumK有关的问题。 1.两数之和 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 使用一个map用来存储数组元素值以及下...

大魔王 730

利用R批量计算相关系数

批量求相关系数

weixin_52073820的博客 1463

分布式一致性机制整理

分布式中一致性是非常重要的,分为弱一致性和强一致性。现在主流的一致性协议一般都选择的是弱一致性的特殊版本:最终一致性。下面就从分布式系统的基本原则讲起,再整理一些遵循这些原则的协议或者机制,争取通俗易懂。但是要真正实施起来把这些协议落地,可不是一片文章能说清楚的,有太多的细节,要自己去看论文呐(顺着维基百科找就行了)。 基本原则与理论 C...

weixin_34268610的博客 374

华为OD机试新系统真题 - 电池充电时间计算

华为OD机试 新系统真题【电池充电时间计算】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题【电池充电时间计算】多语言题解。

qq_45776114的博客 551

【数字孪生与仿真技术】10:半导体制造中的虚拟量测技术深度解析:从多尺度建模到工业级应用

摘要:半导体制造过程中,晶圆加工需实时监测300+关键参数,传统物理量测技术面临产能损耗、延迟检测等痛点。本文系统阐述虚拟量测(Virtual Metrology)技术的完整解决方案,通过多尺度混合建模实现物理机理与数据驱动的深度融合。内容涵盖等离子体刻蚀、薄膜沉积等关键工艺的物理模型构建,LSTM神经网络的数据校正算法,以及边缘-云协同的实时部署架构。某12英寸晶圆厂实践表明,虚拟量测技术可减少70%物理量测频次,异常漏检率从18%降至3%,机台利用率提升11%。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 2576

Leetcode #18 4Sum 四数之和 解题小节+K-Sum思想

1题目理解Leetcode不少题目是成一个体系的,这道题是找四数之和等于四数之和的题,之前还有2Sum和3Sum,我也已经做了题目的小节,可以点开进行查看。 Leetcode #15 3Sum 三数之和 解题小节 Leetcode #1 Two Sum 解题小结和之前的问题一样,有如下的限制: 1、最终输出的顺序是非降序的(所以我们首先需要排序) 2、不能输出重复的解(所以我们要注意移动)

MebiuW的专栏 4152

论文复现5:UMI Universal Manipulation Interface

UMI 采用手持式夹具,加上精心的界面设计,可实现便携式、低成本和信息丰富的数据收集,以进行具有挑战性的双手和动态操作演示。配备这些功能后,UMI 框架解锁了新的机器人操作功能,只需更改每个任务的训练数据,即可实现零样本可推广的动态、双手、精确和长视野行为。我们通过全面的现实世界实验展示了 UMI 的多功能性和有效性,其中通过 UMI Zeroshot 学习的策略在对不同的人类演示进行训练时可以推广到新的环境和对象。项目主页:https://umi-gripper.github.io/

github_38060285的博客 1999

【力扣Leetcode题解系列之0018—4Sum 四数之和】

《四数之和问题:多语言实现与优化》摘要: 本文探讨了LeetCode第18题"四数之和"的解决方案。通过排序预处理和多指针技术,将时间复杂度从O(n⁴)优化至O(n³)。核心算法采用双层循环确定前两个数,内层使用双指针寻找后两个数,并配合严格的去重机制保证结果唯一性。文章提供了Python、Java和C三种语言的完整实现:Python使用嵌套while循环处理指针移动和去重;Java利用ArrayList存储结果并实现类似逻辑;C版本则通过动态内存分配和qsort排序处理数组。各实现均遵

youngerwang的博客 1585

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

【算法】2SUM/3SUM/4SUM问题

之前就总结过一些Leetcode上各种sum问题,今天再拿出来完整得总结一番。 nSUM问题是指,在一个数组中,找出n个数相加和等于给定的数,这个叫做nSUM问题。 常见的有2SUM,3SUM,4SUM问题,还有各种SUM问题的变种. Leetcode上SUM问题包括: 1. 2SUM 15. 3Sum 16. 3Sum Closest 18.

haolexiao的专栏 2万+

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

leetcode -18 4Sum

4Sum   Given an array S of n integers,are there elements a, b, c, and d in S such that a + b + c + d =target? Find all unique quadruplets in the array which gives the sum of target.   给定一个数组S里包含

laeen的博客 230

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【LeetCode】解题18:4Sum

LeetCode解题 18:4Sum Problem 18: 4Sum [Medium]解题思路Solution (Java) Problem 18: 4Sum [Medium] Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a...

Fayedily的博客 195

LeetCode 18. 4Sum

LeetCode 18. 4SumDescriptionExampleNoteCodeConclusion Description Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? F...

gq__97的博客 404

LeetCode: 18. 4Sum

题目: LeetCode:18. 4Sum 描述: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of ...

dbb191379的博客 182

Leetcode18:4Sum

Leetcode18:4Sum 题目描述:4Sum 简而言之,找出数组中和为指定值的四个数,且不能有重复。 双指针 解题过程 其实此题之前还有三数和,与指定值最相近的三数和,这两题大同小异。这一四数和,其实也差不多,有了前面题目的铺垫,第一想法就是用双指针的方法。 自己的想法是,设定了两个双指针,初始为l1=0,r1=nums.length-1; l2=l1+1,r2=r1-1;然后先进行内部双指...

qq_24367757的博客 135

LeetCode 18 - 4Sum

一、问题描述 Description: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which give...

dbbaq24022的专栏 114

Leetcode 18 - 4Sum

题目 https://leetcode.com/problems/4sum/ 题意 给出一个整数序列和一个数值target,对于这个序列中任意四个数有可能等于target。 请返回和等于target的四个数的所有情况。 Example: Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ ...

weixin_33898876的博客 112

leetcode 18. 4Sum

''' 给定输入数组,输出4元对列表,列表中每个元素是一个列表,子列表数值之和为target ''' class Solution: def fourSum(self, nums, target: int): def select_sort(nums): # 对输入数据进行选择排序 # 选择排序算法是对冒泡排序算法的改进 ...

WYXHAHAHA123的博客 209

[LeetCode 18] 4Sum

Given an arraynumsofnintegers and an integertarget, are there elementsa,b,c, anddinnumssuch thata+b+c+d=target? Find all unique quadruplets in the array which gives the sum oftar...

ExcitedZhang的博客 113

LeetCode-18:4 Sum (四数的和)

给定数组,返回数组中和为target的四元组

大树先生的博客 1212
上一篇: 高等数学——导数的定义和常见导数
下一篇: 分布式专题——判断因果关系的向量时钟算法
TechFlow
博客等级 码龄7年 347粉丝 275原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址