题面

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.

给定数组,找出并返回最接近target的三个元素的和。可以假设,只有一个解。

样例

Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

思路

我们在15题 3Sum中做过,三数加和为target的问题,采用了Two-Point逼近的方法。本题我们稍加改动就可以解决。

1. 数组排序,固定一个元素i,通过两点法去[i+1, size()-1]中搜索另外两个数字,先计算他们的和;

2. 若sum == target,直接返回;若不等,就需要判断sum与 我们给的初值res 那个更加接近target,即判断 abs(sum - target)  与 abs(res - target)的大小,对res进行更新,另外注意 l 和 r 的更新。

3. 返回res.

源码

 class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int len = nums.size();
if(len < )
return ;
//数组升序排序
sort(nums.begin(), nums.end());
int res = nums[]+nums[]+nums[];
for(int i=; i<len; i++)
{
if(i> && nums[i]==nums[i-])
i++;//避免i的重复,不必要
int l = i+, r = len-;
while(l < r)//两点法搜搜
{
int sum = nums[i] + nums[l] + nums[r];
if(sum == target)
return sum;
else if(sum > target)
{
if(abs(sum - target) < abs(res - target))
res = sum;
r--;
}
else
{
if(abs(sum - target) < abs(res - target))
res = sum;
l++;
}
}
}
return res;
}
};

最新文章

  1. Android之弹出/隐藏系统软键盘
  2. A - The Moronic Cowmpouter
  3. go gomail
  4. EChars学习-2
  5. Spring学习笔记之整合hibernate
  6. media type与media query
  7. hdu4435 charge-station(先建后拆+bfs)
  8. hdoj 2767 Proving Equivalences【求scc&amp;&amp;缩点】【求最少添加多少条边使这个图成为一个scc】
  9. hdu 4445 Crazy Tank (暴力枚举)
  10. [自制操作系统] 原子操作&核间中断&读写锁&PRWLock
  11. Android程序启动过程深入解析
  12. shiro的登陆认证(shiro项目中来的一)
  13. C语言二维数组作业
  14. 强制不使用“兼容性视图”的HTML代码
  15. Nodejs 安装 on centos7
  16. python dash 初探 --- k 线国内版
  17. what&#39;s the python之基本运算符及字符串、列表、元祖、集合、字典的内置方法
  18. NOIP2018濒死记
  19. 【转】Redis 总结精讲 看一篇成高手系统-4
  20. 纯CSS实现3D图像轮转

热门文章

  1. Qt编写控件属性设计器8-网络采集
  2. 【417】一条语句编译并执行C语言
  3. asp.net下Response.ContentType类型汇总
  4. 【转载】【游戏开发】在Lua中实现面向对象特性——模拟类、继承、多态
  5. 【转载】利用Amazon ECR和ECS部署容器应用
  6. Red Hat Enterprise 6.5 在虚拟机上将系统语言修改为中文
  7. ORACLE创建表空间和用户,并分配权限
  8. linux下使用Oracle常用命令
  9. [转帖]nginx location配置详细解释
  10. Appium+python启动虚拟机上的app