首页 技术 正文
技术 2022年11月12日
0 收藏 614 点赞 3,155 浏览 929 个字

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).

题意:给定值target,在数列中找到三个数,它们的和最接近这个target。

思路:类似于Two sum、3sum还有本题,都可以先排序后,用夹逼法则:使用两个指针,从前向后,从后向前的遍历,找到符合条件的情况。为什么要使用这种方法了?针对本题,若是固定一个,然后再固定一个,通过移动最后一个指针,找到最小的差,然后,在重新将第二个指针移动一个位置,低三个指针,再重新遍历,这样耗时严重。利用好,已将数组排序这一条件,固定一个数,剩下的两个数分别从头和尾向中间遍历,若是三者的和大于target,则尾指针向左移动,减小对应的值,否则前指针右移增大对应的值,从而增大三者和。与此同时,更新和target最小的差和对应的sum。代码如下:

 class Solution {
public:
int threeSumClosest(vector<int> &num, int target)
{
int sum=num[]+num[]+num[];
int diff=abs(sum-target);
sort(num.begin(),num.end()); for(int i=;i<num.size();++i)
{
int l=i+,r=num.size()-;
while(l<r)
{
int temp=num[i]+num[l]+num[r];
int newDiff=abs(temp-target); if(diff>newDiff)
{
diff=newDiff;
sum=temp;
}
if(temp>target)
r--;
else
l++;
}
}
return sum;
}
};
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860