LeetCode16. 最接近的三数之和

【Leetcode】16. 最接近的三数之和 该算法通过排序和双指针技术,巧妙地在三数之和问题中寻找最接近目标值的组合,避免了暴力枚举的高时间复杂度。 阅读详情

给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。

返回这三个数的和。

假定每组输入只存在恰好一个解。

示例 1:

输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
示例 2:

输入:nums = [0,0,0], target = 1
输出:0
 

提示:

3 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
-104 <= target <= 104

void main() {
  List<int> nums = [4, 0, 5, -5, 3, 3, 0, -4, -5];
  int target = -2;
  // nums = [1, 1, 1, 0];
  // target = -100;
  print(threeSumClosest(nums, target));
}

int threeSumClosest(List<int> nums, int target) {
  nums.sort();
  int result = nums[0] + nums[1] + nums[2];
  for (int i = 0; i < nums.length - 2; i++) {
    int left = i + 1;
    int right = nums.length - 1;
    while (left < right) {
      int closeNum = nums[i] + nums[left] + nums[right];
      if ((closeNum - target).abs() < (result - target).abs()) {
        result = closeNum;
      }
      if (closeNum > target) {
        right--;
      } else if (closeNum < target) {
        left++;
      } else {
        return target;
      }
    }
  }
  return result;
}

LeetCode16. 最接近的三数之和
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

【中等】力扣算法题解析LeetCode16:最接近的三数之和 给定一个整数数组和目标值,找出三个数的和最接近目标值的组合。通过排序和双指针法优化搜索过程:外层循环固定一个数,内层使用双指针寻找剩余两数。通过最小/最大和优化提前终止无效循环,跳过重复元素减少计算。时间复杂度O(n²),空间复杂度O(1)。Java实现中,排序后遍历数组,结合双指针和剪枝策略高效求解,确保返回唯一最接近的和。 阅读详情

相关推荐

Carsim和Matlab/Simulink联合仿真时Carsim匹配不到Matlab的解决方法

      本人使用Carsim和Matlab/Simulink联合仿真做过用机器学习方法解决ACC和简单换道的仿真,曾将8.02 2016 2018三个版本Carsim反复安装N次,有相同方向的同学或安装过程遇到问题的同学可以加本人qq505625869一起交流经验心得。 一.前言       Carsim是一款很好的联合仿真软件,使用Carsim,可以避免搭建很多非常复杂的动力学模型

Kaikai_Liao的博客 8767

『力扣刷题』16_最接近的三数之和 解题代码

html: embed_local_images: true embed_svg: true offline: true toc: undefined print_background: false export_on_save: html: false date: 2019-12-01 updated: 2019-12-01 categories: 力扣刷题 title: 『力扣刷题』...

Paradox 382

别再手动算重量了!用C++给UG/NX写个自动计算零件质量与质心的插件(附完整源码)

本文详细介绍了如何使用C++为UG/NX开发智能质量分析插件,实现零件质量与质心的自动计算。通过结合NXOpen和UF_MODL API,设计高效的数据结构和批量处理机制,大幅提升机械设计效率。文章包含完整源码和实用技巧,帮助工程师告别手动计算,适用于复杂装配体的自动化工程计算。

weixin_30247307的博客 131

leetcode-16. 最接近的三数之和

通过排序加双指针法,我们能够高效地解决三数之和最接近(3Sum Closest)的问题。该方法利用数组的有序性,通过双指针在固定一个元素的基础上快速查找剩余两个元素,以找到最接近目标值的和。关键步骤回顾:排序数组,简化搜索过程。固定第一个元素,使用双指针查找剩余两个元素。在查找过程中持续更新最接近的和。合理移动指针以优化搜索效率。掌握此类技巧,不仅有助于解决类似的编程问题,还能加深对双指针法和排序在算法中的应用理解。

qq_39370495的博客 849

UE5动画革命:如何用Motion Matching技术让你的游戏角色动作更流畅(附实战配置)

本文深入解析了UE5中Motion Matching技术的实战配置与应用。通过对比传统动画状态机的局限,详细阐述了如何构建动画数据库、在UE5中配置Pose Search Database及动画蓝图,并探讨了与IK融合、性能优化等进阶策略。该技术能显著提升游戏角色动作的流畅度与真实感,是下一代动画解决方案的核心。

weixin_29075633的博客 862

低速信号设计之 ESPI 篇

ESPI 是 Intel 推出的增强型串行外设接口,基于 SPI 发展而来,新增 Reset# 和 Alert# 信号,采用点对点主从通信模型,最高速率达 33MHz,支持半双工与 DMA 传输。 其物理接口含 10 条线路,通信协议分物理层、数据链路层等四层。布局布线需关注信号完整性、电源完整性,还得考虑与 SPI 的兼容性。 ESPI 广泛应用于计算机系统(连接 BIOS、电源管理器等)和工业控制领域,具有引脚少、功耗低等优势,但设计复杂且存在兼容性挑战。

qq_16237389的博客 1382

leetcode 16. 最接近的三数之和(C++)

leetcode 16. 最接近的三数之和(C++):

nanashi_F的博客 293

500道C++面试高频题解析(附答案、实战示例与进阶追问)

本文提供500道C++面试高频题的详细解析,涵盖基础概念到进阶应用,包括面向对象编程、内存管理、现代C++特性、并发编程等核心考点。每道题配有实战示例和进阶追问,帮助开发者突破八股文局限,掌握解决实际问题的能力,适合准备C++技术面试的工程师系统复习。

weixin_29002595的博客 311

LeetCode16.最接近的三数之和 JavaScript

LeetCode16.最接近的三数之和 JavaScript 给定一个包括 n个整数的数组 nums 和 一个目标值target。找出nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 ...

weixin_34024034的博客 223

群晖NAS安装HomeAssistant保姆级教程:从Docker部署到智能设备接入

本文提供了一份详尽的群晖NAS安装HomeAssistant保姆级教程,涵盖从Docker部署到智能设备接入的全过程。通过规划存储路径、配置容器环境变量和网络模式,确保系统稳定运行。教程还介绍了如何接入小米、苹果HomeKit等智能家居设备,并利用自动化与仪表盘打造本地化、高响应速度的智能中枢,实现数据隐私与远程控制的完美平衡。

play7的博客 694

基于机器学习的网络入侵检测系统设计与实现

本文设计并实现了一个基于机器学习的网络入侵检测系统,采用随机森林模型结合KMM算法优化,使用CICIDS2017数据集进行训练。系统包含完整的数据预处理流程、特征工程、模型调优和远程部署方案。实验结果表明,该系统能有效识别多种网络攻击类型,在检测准确率和误报率方面表现优异。研究为网络安全防护提供了新的技术思路和实用工具,具有重要的应用价值。

huanghm88的专栏 318

力扣(LeetCode 16)最接近的三数之和 python

题目 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2...

qq_41318002的博客 419

OpenClaw实战一|企业微信AI客服数字员工:自动应答+工单创建+数据统计,零代码3天落地

OpenClaw做企业微信AI客服数字员工,真正的价值不是“能自动回复”,而是把“咨询-应答-工单-统计-复盘”全流程闭环。对中小企业来说,不用招专职AI开发、不用买昂贵客服系统,一台服务器、零代码配置,就能拥有媲美大厂的智能客服能力。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 517

【LeetCode】16. 最接近的三数之和

这道题要求从数组中找出三个数,使其和最接近目标值。核心解法是排序+双指针:先排序数组,然后固定一个数,用双指针寻找另外两个数,计算三数之和与目标的差值,不断更新最接近值。时间复杂度为O(n²),空间复杂度O(1)。关键优化包括跳过重复元素和剪枝处理。该算法适用于数值逼近、优化问题等场景,是经典的双指针应用范例。

qq_32019341的博客 1040

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

LeetCode 16最接近的三数之和

LeetCode 16最接近的三数之和 题目简述:给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 nums = [-1, 2, 1, -4] target = 1 输出:2(-1+2+1=2) 思路一:暴力解法O(n3) 暴力三重循环枚举下标i,j,k,然后判断nums[i] + nums[j] + nums[k]是否与target更接近 class

XBlog 142

深度学习工具包 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第16题最接近的三数之和

力扣LeetCode第16题最接近的三数之和

weixin_44061444的博客 544

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

LeetCode第 16 题:最接近的三数之和(C++)

16. 最接近的三数之和 - 力扣(LeetCode) 假定每组输入只存在唯一答案。 有了上面的假定,可以知道数组中不存在重复元素,和上一题LeetCode第 15 题:三数之和(C++)很像,只是这题target不再固定为0,而且需要寻找最接近的。 不过思路都是一样的,排序之后固定第一个元素,然后使用双指针从两头往中间检索: class Solution { public: int threeSumClosest(vector<int>& nums, int target) {

zj 645

LeetCode16-最接近的三数之和

LeetCode16-最接近的三数之和 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). 一、思...

lyd1995的博客 178

[leetcode_16_threeSumClosest] 力扣第16题 最接近的三数之和

力扣第16题 最接近的三数之和

C_0010的博客 933

力扣第16题:最接近的三数之和

学习目标: 力扣第16题:最接近的三数之和 学习内容: 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 示例: 输入:nums = [-1,2,1,-4], target = 1 输出:2 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/probl

童一的博客 300

力扣LeetCode #16 最接近的三数之和(ThreeSumClosest)

- 题目描述 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 提示: 3 <= nums.length <= 103 -103 <= nums[i] <= 103 -104 <= target <= 104 来源:LeetCode(https://leetcode-cn.com/problems/3sum-closest) - 示例

weixin_49155948的博客 289

#力扣 LeetCode16. 最接近的三数之和 @FDDLC

题目描述: 16. 最接近的三数之和 - 力扣(LeetCode) (leetcode-cn.com) 自测用例: [-1,2,1,-4] 1 [-1,2,1,-4] 2 [-1,2,1,-4] 3 [-1,2,1,-4] 4 [-1,2,1,-4] 5 [-1,2,1,-4] -7 Java代码一: class Solution { public int threeSumClosest(int[] a, int t) { int ans=a[0]+a[1]+

LiuXingchang的博客 319

力扣(LeetCode)16. 最接近的三数之和(C++)

【墨染】快排+双指针

墨染 337
上一篇: LeetCode15. 三数之和
下一篇: LeetCode17. 电话号码的字母组合
番茄巧克力
博客等级 码龄9年 3粉丝 52原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值