LeetCode | 16. 3Sum Closest

告别抓包失败!保姆级配置:让Burp+Proxifier稳定抓取任意微信小程序 本文提供了一套完整的Burp+Proxifier配置方案,确保稳定抓取微信小程序数据。从环境准备、工具选型到Burp Suite深度配置和Proxifier精准设置,详细解决了证书安装、进程捕获和乱码解析等核心问题,帮助开发者告别抓包失败,提升调试效率。 阅读详情

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 one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

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

提供三种思路.

第一种,朴素的O(n^3)加一点优化,106ms擦边AC,(击败1.56%的人23333)

class Solution {
public:
        int threeSumClosest(vector<int>& nums, int target)
        {
            int res = 0;
            int delta = 999999;
            int len = nums.size();
            sort(nums.begin(),nums.end());
            for(int i=0;i<len;i++)
            {
                for(int j=i+1;j<len;j++)
                {
                    int tsum = nums[i]+nums[j];
                    for(int k=j+1;k<len;k++)
                    {
                        if(abs(tsum+nums[k]-target) < delta)
                        {
                            delta = abs(nums[i]+nums[j]+nums[k]-target);
                            res = nums[i]+nums[j]+nums[k];
                        }
                        if(tsum+nums[k] > target)
                        {
                            break;
                        }
                    }
                }
            }

            return res;
        }

};







第二种,类似3SUM问题,对于某一确定的值T,利用O(N^2)算法判断nums中是否存在三个数和为T.如果存在,返回T.这个T,是从给定的Target开始,左右浮动,设它上限为10000,复杂度为O(c * N^2),9ms AC,排名基本上在前10%了

class Solution {
public:
        bool find(vector<int>& v, int sum)//判断是否存在和为sum的三个数 O(n^2)
        {
            int len = v.size();
            for(int i=0;i<len;i++)
            {
                int left = i+1, right = len-1;
                while(left < right)
                {
                    if(v[left]+v[right] == sum-v[i])
                    {
                        return true;
                    }
                    else if(v[left]+v[right] < sum-v[i])
                    {
                        left++;
                    }
                    else
                    {
                        right--;
                    }
                }
                while(v[i]==v[i+1])
                {
                    i++;
                }
            }
            return false;
        }

        int threeSumClosest(vector<int>& nums, int target)
        {
            int res = 0;
            sort(nums.begin(),nums.end());
            for(int i=0;i<10000;i++)
            {
                if(find(nums,target+i))
                {
                    return target+i;
                }
                if(find(nums,target-i))
                {
                    return target-i;
                }
            }

            return res;
        }

};







第三种,参考大神们提供的思路,类似3Sum的两个指针.

----------------------------------------------------
^  ^                                               ^
|  |                                               |
|  +- second                                     third
+-first

if nums[first] + nums[second] + nums[third] is smaller than the target, we know we have to increase the sum. so only choice is moving the second index forward.

----------------------------------------------------
^    ^                                             ^
|    |                                             |
|    +- second                                   third
+-first

if the sum is bigger than the target, we know that we need to reduce the sum. so only choice is moving ‘third’ to backward. of course if the sum equals to target, we can immediately return the sum.

----------------------------------------------------
^    ^                                          ^
|    |                                          |
|    +- second                                third
+-first

when second and third cross, the round is done so start next round by moving ‘first’ and resetting second and third.

----------------------------------------------------
  ^    ^                                           ^
  |    |                                           |
  |    +- second                                 third
  +-first

while doing this, collect the closest sum of each stage by calculating and comparing delta. Compare abs(target-newSum) and abs(target-closest). At the end of the process the three indexes will eventually be gathered at the end of the array.

----------------------------------------------------
                                         ^    ^    ^
                                         |    |    `- third
                                         |    +- second
                                         +-first

if no exactly matching sum has been found so far, the value in closest will be the answer.

class Solution {
public:
        int threeSumClosest(vector<int>& nums, int target)
        {
            int len = nums.size();
            int delta = 99999;
            int res = 0;
            sort(nums.begin(),nums.end());
            for(int i=0;i<len;i++)
            {
                int left = i+1, right = len-1;
                while(left < right)
                {
                    int tsum = nums[left]+nums[right]+nums[i];
                    if(abs(target-tsum) < delta)
                    {
                        delta = abs(target-tsum);
                        res = tsum;
                    }
                    if(tsum == target)
                    {
                        return target;
                    }
                    else if(tsum < target)//移动左边的指针
                    {
                        left++;
                    }
                    else
                    {
                        right--;
                    }
                }
            }

            return res;
        }

};
Coze智能体开发:如何搭建一个生成长文本的工作流 扣子工作流提供了流程定制化的能力,我们可以把长文生成的流程拆分为多个步骤,例如先通过大模型节点生成大纲、再使用循环节点依次扩写各个段落,最后将各个段落组合起来,从而实现长文生成流程。此工作流可适用于学术写作、商业报告、小说创作等多种场景。 阅读详情

相关推荐

基于FPGA的图像预处理系统(图)

 北京机械工业学院 韩娟娟 邓文怡 娄小平 由于获取图像的工具或手段的影响,使获取图像无法完全体现原始图像的全部信息。因此,对图像进行预处理就显得非常重要。预处理的目的是改善图像数据,抑制不需要的变形或者增强某些对于后续处理来说比较重要的图像特征。通常根据预处理目的的不同,把预处理技术归为图像增强技术和图像分割技术两类。图像对比度处理是空间域图像增强的一种方法。由于图像灰度范围狭窄会使

lyzhangxianglove的专栏 1780

Add Two Numbers

Number of 1 Bits iven an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. For

github_30830155的博客 363

总结所有的池化(Pooling)方法

为什么池化? 池化(Pooling)层和卷积层、全连接层一样,都是卷积神经网络的组成部分。 卷积神经网络中的卷积层会将卷积Filter应用于输入图像,以便创建特征映射来总结输入中这些特征的存在。 卷积层被证明是非常有效的,在深层模型中叠加卷积层可以让接近输入的层学习低层特征(如线条),在模型中更深(高)的层用于学习高阶或者更抽象的特征,如形状或特定对象。 卷积层特征映射输入的一个局限性是它们只能精确记录特征在输入层的位置。这意味着在输入图像中特征位置的小幅移动将导致不同的特征映射。这可以随着重新裁剪

大脸猫的博客 1万+

哈希表 Given an array of integers, return indices of the two numbers such that they add up to a specif

Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same ...

qq_35975827的博客 2735

整理并记录几种运算放大器

运算放大器是一种十分常见的电子元器件,最近我在学习运放,以前在学校没有好好的学习,今天在B站看了唐老师讲运算放大器-唐老师讲电赛系列视频教程,记录下所学的,纯当是自己的笔记 学习运放,有两个重要的概念及重要的计算法宝,虚短vp=vn;和虚断ip=in 1反向比例运算电路 Rf可以大于、小于或等于R,起到放大、跟随、衰减输入的作用; 平衡电阻没有太高的精度要求,可加可不加; 有些运放内部集成了补偿电路,就不需要使用平衡电阻,加了反而增大误差,如OPA227 2.同向比例运放电路 .

qq_36823004的博客 6369

OpenCV透视变换实战:5分钟搞定歪斜证件照矫正(附完整代码)

本文详细介绍了如何使用OpenCV的透视变换技术快速矫正歪斜证件照,包含完整的Python代码实现。通过特征检测、坐标计算和矩阵变换三个核心步骤,5分钟内即可将手机拍摄的歪斜图像自动矫正为专业级证件照,大幅提升图像处理效率。

weixin_29094979的博客 483

《LeetBook》leetcode题解(15):3Sum[M]

015. 3Sum问题Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.Note: Elements in a triplet (a,b,c

Voidsky 1172

湿式双离合器自动变速器simulink建模与仿真

随着汽车工业的不断发展,自动变速器在提高汽车性能、驾驶舒适性和燃油经济性等方面发挥着越来越重要的作用。湿式双离合器自动变速器(Wet Dual-Clutch Transmission,简称 WDCT)作为一种先进的自动变速器技术,具有换挡速度快、动力传递平稳、燃油经济性好等优点,被广泛应用于各类汽车中。结构组成湿式双离合器自动变速器主要由双离合器、齿轮传动系统、液压控制系统和电子控制系统等部分组成。双离合器:由两个独立的离合器组成,分别控制奇数挡和偶数挡。通过切换两个离合器的工作状态,可以实现快速换挡。

平时工作较为繁忙,私信消息一般晚上回复,谢谢大家~~ 348

面试题:Two Sum

Given an array of integers, returnindicesof the two numbers such that they add up to a specific target. You may assume that each input would haveexactlyone solution, and you may not use thesame...

weixin_30590285的博客 137

5、数据计算与处理技巧全解析

本文深入解析了Tableau中的多种数据计算与处理技巧,涵盖LOD计算、日期与字符串处理、计数优化、数据混合限制及自定义总计等核心内容。通过实际案例和流程图,系统讲解了各技巧的应用场景、实现步骤与注意事项,并提供性能优化建议和常见问题解答,帮助用户提升数据分析效率与可视化精度。同时展望了未来数据计算技术的发展趋势,是Tableau用户进阶必备的全面指南。

peach的博客 83

Windows10环境下激活虚拟环境报错【source : 无法将“source”项识别为 cmdlet、函数、脚本文件或可运行程序的名称】

在使用Django创建Web程序前,需要创建一个虚拟的工作环境,在使用【source ll_env/bin/activate】命令激活虚拟环境时报错:source : 无法将“source”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。所在位置 行:1 字符: 2。

提供C#相关开发 、云计算、运维测试、网络安全相关技术分享与服务,有意向可联系。 1万+

LeetCode 16. 3Sum Closest 题解

本题是三数之和问题的变种,主要考察对排序和双指针技巧的理解和使用。通过排序和双指针,我们可以有效地找到与目标值最接近的三数之和。排序的核心思想是将数组按照升序排列,这样我们可以使用双指针来高效地查找和调整三数之和。双指针的核心思想是:通过移动左指针和右指针,我们可以根据当前和与目标值的关系来调整指针的位置,从而找到最接近的和。这种方法不仅适用于最接近的三数之和问题,还可以应用于许多其他需要查找最接近值的问题。掌握排序和双指针的使用,对于解决这类问题非常重要。

cannonjinx的博客 4297

Xilinx DDR3 MIG IP核设计--汇总导航

快速上手Xilinx DDR3 IP核----汇总篇

孤独的单刀 2万+

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的博客 363

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

leetcode 16:3Sum Closest with python

import sys class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort()...

dxcve的博客 200

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

LeetCode:16. 3Sum Closest

LeetCode:16. 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 ass...

Wisimer 174

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

leetcode解题报告16. 3Sum Closest

leetcode解题报告16. 3Sum Closest题目地址 难度是medium题目描述和3SUM问题类似,输入一个整数数组,和一个目标整数target。从数组中选择3个数,使得这三个数之和最接近target。要求返回这三个数之和即可,不要求具体返回是哪三个数。默认有且只有一个解。我的思路同样地最简单的方法是三层循环暴力遍历即可。但是这一般不是我们相要的答案。 和3sum问题相比,其实我们可以

sysu_xiaoming的博客 466

Leetcode 16. Closest 3 Sum

题目名称:16. Closest 3 Sum 难度:Medium 知识点:双指针 解题思路:这道题特点是只需返回最靠近的三个数字的和,因此我们可以对数组进行排序,排序之后遍历整个数组,其中的每个数字作为第一个数字,求其与目标和的差值,在剩余的数字中寻找最靠近的差值,因为数组已经排序,因此可以用双指针,计算每一组三个数字与目标值的距离,如果绝对值比较小,我们就存起来这个值。另外,如果第一个数字的三倍已经比目标和大或者相等了,那我们只要看当前数字和其后面两个数字就好,不需要双指针去寻找了,再有就是我们在调

weixin_54889359的博客 283

LeetCode 16 3Sum Closest 可用三分法

题意:3Sum题变种,给出n个数nums[]和一个target,求n中的3个数的组合使得其和与target相差值最小。 思路:传统的3Sum做法(LeetCode15),枚举三个数中的两个,然后求证剩余的数字是否在给出的集合中。后面一步可以时间换空间,用二分来做,这样复杂度乘上一个logn;也可以空间换时间,用数组直接存储或者hash挂链。 对于这一题,可以继续用传统的解法,先枚举三个数中的两个,但注意到目标答案的变化并不是单调的,即取出两个数nums[i]和nums[j]后,最优解的计算过程为ans=

sluqy671的专栏 273

leetcode 16. 3Sum Closest

leetcode 16. 3Sum Closest class Solution { public int threeSumClosest(int[] nums, int target) { int result=nums[0]+nums[1]+nums[nums.length-1]; Arrays.sort(nums); int i=0; for (i=0; i<nums.length-2; i++){

Weijia_Song的博客 260

LeetCode 力扣:15.3Sum + 16.3Sum Closest + 18.4Sum 排序 + 双指针遍历 题目+算法分析+Cpp解答

15.3Sum 排序 + 双指针遍历: ​ 首先,将给定的数组进行排序(从小到大的顺序)。 ​ 遍历排序后的数组中的每一个数,如果这个数之前已经讨论过了则可以跳过。 ​ 将取出的数作为“目标”,使用双指针在排序后的数组中找另外的两个数: ​ 一个左指针指向该取出的数的后一个数,即此时的最低位。 ​ 另一个右指针指向数组的最后一个数,即此时的最高位。 ​ 由于数组已经是从小到...

WULH 1177

LeetCode第16题思悟——最接近的三数之和(3sum-closest)

LeetCode第16题思悟——最接近的三数之和(3sum-closest) 知识点预告 数组预处理:排序; 双指针遍历数组的处理方法; 题目要求 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 来源:力扣(LeetCode) 链接:https://le...

博采众长,自成一派; 347

LeetCode 16. 3Sum Closest

LeetCode 16. 3Sum ClosestDescriptionExampleCodeConclusion Description Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Retur...

gq__97的博客 302

LeetCode No.16 3Sum Closest

LeetCode No.16 3Sum Closest

黄健伟的博客 985
上一篇: LeetCode | 15. 3Sum(三数和为定值)
下一篇: LeetCode | 17. Letter Combinations of a Phone Number
PKU_CXK
博客等级 码龄10年 87粉丝 142原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值