[LeetCode] (medium) 16. 3Sum Closest

RYU+Mininet的SDN架构-设计校园网络(一) 现有一个中学,需要设计一个中小型网络满足学校的网络需求。学校有教学区,实验室区域和服务器区域。教学区为了满足接入的灵活性和信号强度要求,需要满足设计WIFI满足日常教室和同学需求,接入上限为200人。实验室区域需要有一台教师主机方便管理实验室其余电脑,并且教师主机可以访问学校服务器,方便为同学们实验室授课。学校服务器区域设有学校相关重要文件和学校网页相关内容。最后学校还会接入互联网。 阅读详情

https://leetcode.com/problems/3sum-closest/

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

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

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

题目本身很简单,使用和3sum同样的方法就可以,问题的重点同样在与细节的优化

但是注意,在看了最快的提交代码之后发现其中有一处错误,他在最外层循环中直接使用了 if (nums[k] - target > dist) break;来剪枝,乍看之下好像没什么问题(nums[k]已经大于了当前解的上界,而[i][j]只会比[k]更大),但是细想之后就会发现当tar+dis<0时并不能保证后续不会出现更优解(反例:[-5,-4,-3,-2,0], -6,当k=1时)。

我的代码:

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int re_dif = INT_MAX;

        int tem;
        
        int len = nums.size();
        
        int cur;
        
        sort(nums.begin(), nums.end());
        
        for(int i = 0; i < len; ++i){
            cur = nums[i]-target;
            // cout << i << ' ' << cur << endl;
            int lo = i+1;
            int hi = len-1;
            
            while(lo < hi){
                tem = cur+nums[lo]+nums[hi];
                // cout << i << ' ' << lo << ' ' << hi << ' ' << tem << endl;
                if(abs(tem) < abs(re_dif)) re_dif = tem;
                if(tem > 0) --hi;
                else if(tem < 0) ++lo;
                else{
                    return target;
                }
            }
            
        }
        
        return target+re_dif;
    }
};

 

问题代码:

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int dist = INT_MAX, res;
        sort(nums.begin(), nums.end());
        if (nums.size() < 3) return 0;
        for (int k = 0; k < nums.size()-2; ++k) {
            if (nums[k] - target > dist) break;    //就是这一句判断有问题
            if (k > 0 && nums[k] == nums[k - 1]) continue;
            int i = k + 1, j = nums.size() - 1, sum;
            while (i < j) {
                sum = nums[k] + nums[i] + nums[j];
                if (sum == target)
                    return sum;
                else {
                    if (abs(sum - target) < dist) {
                        dist = abs(sum - target);
                        res = sum;
                    }
                    if (sum < target) ++i;
                    else --j;
                }
            }
        }
        return res;
    }
};

 

相关推荐

SRAM:SRAM入门指南与工作原理

SRAM(Static Random Access Memory),即静态随机存取存储器,是一种能够读取和写入数据的内存(RAM)。它使用由晶体管组成的触发器来存储数据,只要有电源供应,数据就可以稳定地保存。与动态随机存取存储器(DRAM)不同,SRAM 不需要周期性地刷新来保持数据。

weixin_42896509的博客 1万+

LeetCode 16. 3Sum Closest (Java版; Medium)

welcome to my blog LeetCode Top Interview Questions 16. 3Sum Closest (Java版; Medium) 题目描述 Given an array nums of n integers and an integer target, find three integers in nums such that the sum i...

littlehaes的博客 362

基于Codex与Skills的学术研究自动化全流程实战指南

还在为海量文献下载、整理、阅读和综述写作而头疼吗?面对堆积如山的PDF,你是否感到无从下手?从选题、文献检索、到写作、绘图、润色,再到应对AI检测和审稿意见,学术研究的每一步都充满挑战。本文将为你带来一套堪称“王炸组合”的解决方案: Codex + Skills 。这不是简单的工具介绍,而是一套从零开始,覆盖学术研究全流程的保姆级实战教程。我们将手把手教你如何安装、配置,并利用强大的Skills(技能)自动化处理文献下载管理、高效撰写综述、生成专业图表、智能润色降重,直至应对审稿。无论你是科研新手还是希望提

weixin_29041195的博客 764

【leetcode】【medium】16. 3Sum Closest

16.3Sum Closest Given an arraynumsofnintegers and an integertarget, find three integers innumssuch that the sum is closest totarget. Return the sum of the three integers. You may assume that...

lemonade13的博客 168

Unity游戏Mono注入实战:从反编译到功能扩展

本文详细介绍了Unity游戏Mono注入的完整实战流程,从使用dnSpy反编译游戏核心逻辑,到编写自定义C#功能DLL,再到利用SharpMonoInjector进行动态注入。文章深入讲解了如何通过Harmony库拦截修改游戏方法,并介绍了使用MelonLoader框架和UnityExplorer进行高级模组开发与调试,最终通过一个游戏对象透视(ESP)案例演示了功能扩展的实现。

weixin_29018335的博客 458

DIY压电陶瓷传感器信号放大:从拆解到JFET电路实战(附示波器实测数据)

本文详细介绍了如何利用废旧设备拆解的压电陶瓷片,结合JFET(结型场效应管)高输入阻抗特性,DIY搭建高灵敏度振动传感器放大电路。从元件拆解、参数实测到JFET共源极放大器实战搭建与调试,提供了完整的步骤、示波器实测数据及优化方案,帮助电子爱好者实现低功耗振动检测应用。

weixin_29195615的博客 389

[Leetcode 16, Medium] 3Sum Closest

[Leetcode 16, Medium] 3Sum Closest

算法的实践 476

手把手教你用C语言实现GNSS卫星方位角计算(附RTKLIB风格代码解析)

本文详细介绍了如何使用C语言实现GNSS卫星方位角计算,包括从地固坐标系到站心坐标系的转换链条。通过RTKLIB风格的代码解析,展示了XYZ到ENU坐标转换的核心原理和C语言实现框架,帮助开发者掌握卫星方位角和高度角的计算技巧,适用于GNSS观测数据质量分析和精密定位算法开发。

weixin_30699915的博客 365

LeetCode:16. 3Sum Closest(Medium)

1. 原题链接 https://leetcode.com/problems/3sum-closest/description/ 2. 题目要求 数组S = nums[n]包含n个整数,找出S中三个整数a,b,c,使得a+b+c=sum,sum最接近给定的目标整数target,返回sum。 3. 解题思路 采用与第15题相同的思路(第15题链接),不过要引入两个整型变量min和r...

aysk1112的博客 228

双硬盘下Ubuntu 16.04与Win10双系统的安装

之前写过一个双系统安装过程,今天再次整理的原因是想重点强调双硬盘的区别。标红的一定要注意看,那就是我自己一步一步踏出来的坑啊...   基础步骤就不再重复,重点讲区别,需要看详细步骤的童鞋(或者你只有一个硬盘)请看我上一篇博客https://blog.csdn.net/weixin_40308540/article/details/80157444   区别:双硬盘和单硬盘的区别是什么呢?...

不吃包子 1124

Python+Appium实现泛微OA自动打卡:5分钟搭建移动端自动化脚本

移动端自动化测试是软件测试与办公自动化领域的重要技术方向,其核心原理是通过程序模拟用户对手机应用界面的操作,实现重复性任务的自动执行。Appium作为主流的开源移动端自动化框架,基于WebDriver协议,支持跨平台且无需修改被测应用,为自动化脚本开发提供了标准化接口。在工程实践中,结合Python简洁的语法和丰富的生态,可以快速构建稳定可靠的自动化解决方案。这一技术组合的价值在于能够高效处理“重复性、低价值、高频率”的日常操作,例如考勤打卡、数据填报等办公场景,显著提升工作效率。本文以泛微OA Emobi

weixin_28836875的博客 390

Leetcode 16. 3Sum Closest [medium][java]

3Sum Closest Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that eac...

inkhk的博客 154

基于Simulink的压缩空气储能(Compressed Air Energy Storage, CAES)

压缩空气储能(CAES)是一种将电能转化为压缩空气存储在高压容器中,然后在需要时释放空气驱动涡轮机发电的技术。它具有大规模、长寿命和环境友好的特点,在电力系统中用于削峰填谷、频率调节和备用电源等应用。本项目将详细介绍如何在MATLAB/Simulink中搭建一个完整的基于压缩空气储能的系统,并提供具体的代码实现和设计步骤。如果你需要实现更复杂的控制逻辑,可以使用MATLAB Function模块。以下是一个简单的例子,展示了如何在该模块中实现一个条件逻辑:Matlab深色版本Kp = 1;

MHD0815的博客 1274

Leetcode 16. 3Sum Closest (Medium) (cpp)

Leetcode 16. 3Sum Closest (Medium) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 449

jre9下载 jdk9

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

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

LeetCode - Medium - 16. 3Sum Closest

Topic Array Two Pointers Description https://leetcode.com/problems/3sum-closest/ Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may as

KISS 205

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

LeetCode_Medium_16. 3Sum Closest

2019.1.27 题目描述: Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that...

weixin_41637618的博客 157

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

LeetCode算法题之16. 3Sum Closest(medium)【Python3题解】

题目描述: Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input ...

DaMoWangZQ的博客 266

LeetCode (力扣) 16. 3Sum Closest (C) - Medium 暴力解、双指标( Merge Sort )、双指标( Quick Sort )

同步发于JuzerTech网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。

JuzerTech的博客 240

Leetcode 16. 3Sum Closest (Medium) (java)

Leetcode 16. 3Sum Closest (Medium) (java)

还是需要多学习!闷声大发财,这是坠吼的! 441

Leetcode 16[medium]--3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly...

fawnzou2017的博客 194

[LeetCode] 16. 3Sum Closest_Medium tag: Array, Two pointers

Given an arraynumsofnintegers and an integertarget, find three integers innumssuch that the sum is closest totarget. Return the sum of the three integers. You may assume that each input would ...

weixin_30421525的博客 98

题解——Leetcode 16. 3Sum Closest 难度:Medium

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exa

dxk3881345的博客 334

Leetcode: 16. 3Sum Closest(Week5, Medium)

学号: 15331204 方向: 数媒 姓名: 林威宏 对称密码有五个组成部分: (1) 明文(M) (2) 密文(C) (3) 密钥(K) (4) 加密算法(E) (5) 解密算法(D) 接下来的内容皆参照以上的符号定义。1. 算法原理概述 DES,即Data Encryption Standard(1) 是一种对称加密算法,典型的DES以64位为分组对数据进行加密,且加密与解密用的是同一

linwh8的博客 448

【LeetCode】 16. 3Sum Closest 最接近的三数之和(Medium)(JAVA)

16. 3Sum Closest 最接近的三数之和(Medium)(JAVA) 题目地址: https://leetcode.com/problems/3sum-closest/ 题目描述: Given an array nums of n integers and an integer target, find three integers in nums such that the sum i...

qq_16927853的博客 187

LeetCode-16-3Sum Closest(证明/KSum)-Medium

题意理解: 求解vector中三个数之和与target的值最接近,其中,假设vector中比存在这样的三个值; 题目分析: 同15-3Sum 解题代码: class Solution { public: int threeSumClosest(vector& nums, int target) { int size=nums.size();

eddy_liu的专栏 540

[array] leetCode-16. 3Sum Closest -Medium

16. 3Sum Closest -Medium descrition Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assum...

weixin_30396699的博客 137
上一篇: [LeetCode] (medium) 378. Kth Smallest Element in a Sorted Matrix395. Longest Substring with At Least
下一篇: [LeetCode] (medium) 18. 4Sum
Frontier_Setter
博客等级 码龄10年 2粉丝 123原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值