题目

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

代码

class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
// sort the num
std::sort(num.begin(), num.end());
// return value & min_gap
int closest_sum = ;
int min_gap = INT_MAX;
// from two sides to mid
for (std::vector<int>::iterator i=num.begin(); i!=num.end()-; ++i)
{
std::vector<int>::iterator j = i+;
std::vector<int>::iterator k = num.end()-;
while(j<k)
{
const int sum = *i+*j+*k;
const int gap = std::abs(target-sum);
if (gap < min_gap)
{
closest_sum = sum;
min_gap = gap;
}
// move according to the sum and target
if (sum<target)
{
++j;
}
else if (sum>target)
{
--k;
}
else
{
return target;
}
}
}
return closest_sum;
}
};

Tips:

1. 方法就是:“先排序,再夹逼”这是一种时间复杂度为O(n²),空间复杂度为O(1)的常用技巧

2. 方法的实现技巧是设置头尾两个pointer,根据sum与target的关系大小选择指针move的方向

3. 为什么要先排序再夹逼?因为可以根据sum与target关系调整大小,使其每次计算都能有目标地移动。这样每次遍历保证能得到包含*i在内的最优sum。

==================================================

第二次过这道题,有了3Sum的基础之后,这道题的思路也就有了。

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int ret = ;
if (nums.size()< )
{
for ( int i=; i<nums.size(); ++i ) ret += nums[i];
return ret;
}
ret = nums[]+nums[]+nums[nums.size()-];
std::sort(nums.begin(), nums.end());
for ( int i=; i<nums.size()-; ++i )
{
if ( i> && nums[i]==nums[i-] ) continue;
int begin = i+;
int end = nums.size()-;
while ( begin<end )
{
int value = nums[i]+nums[begin]+nums[end];
if ( value<target )
{
ret = abs(ret-target)>abs(value-target) ? value : ret;
begin++;
while ( begin<end && nums[begin-]==nums[begin] ) begin++;
}
else if ( value>target )
{
ret = abs(ret-target)>abs(value-target) ? value : ret;
end--;
while ( begin<end && nums[end]==nums[end+] ) end--;
}
else
{
return target;
}
}
}
return ret;
}
};

tips:

大体思路还是“排序+双指针夹逼”

具体的做法就是每次算一个可能的更贴近结果的和后,就检查一次要更新返回的值。

上述的代码有些麻烦了。

如果不直接维护返回值,而是维护一个与target的差值,这样就省去了很多麻烦。而这种简便一些的思路是第一次学习别人代码AC的思路。

【3Sum Closest 】cpp的更多相关文章

  1. hdu 4739【位运算】.cpp

    题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...

  2. Hdu 4734 【数位DP】.cpp

    题意: 我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+...a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字. 题目给出a,b,求出0~ ...

  3. 【Valid Sudoku】cpp

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  4. 【Permutations II】cpp

    题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...

  5. 【Subsets II】cpp

    题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...

  6. 【Sort Colors】cpp

    题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...

  7. 【Sort List】cpp

    题目: Sort a linked list in O(n log n) time using constant space complexity. 代码: /** * Definition for ...

  8. 【Path Sum】cpp

    题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...

  9. 【Symmetric Tree】cpp

    题目: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). F ...

随机推荐

  1. 使用CMake生成VS2010项目查看OpenCV源代码

    近期项目需要用到OpenCV中的几个函数,但其函数无法全部实现自己需要的功能,故而需要改进部分函数,为安全及效率起见,想参考OpenCV的源码来改进,这样节省时间的同时亦可提供代码的鲁棒性和通用性.那 ...

  2. tomcat jdk官网下载教程

    Tomcat不同版本官网下载: 1.官网地址:http://tomcat.apache.org/ 2.点击要下载的版本进入下载页,点击Archives进入版本选择页,然后选择对应的版本文件夹,进去后点 ...

  3. System Center Configuration Manager 2016 域准备篇(Part4)

    步骤4.创建系统管理容器 注意:在Active Directory域控制器服务器(AD01)上以本地管理员身份执行以下操作 有关您为何这样做的详细信息,请参阅https://docs.microsof ...

  4. c++ STL deque容器成员函数

    deque是双向队列,即可以在头部插入删除,也可以在尾部插入删除.内部并不连续,这一点和vector并不一样.可能第1个元素和第2个元素的地址是不连在一起的.在使用时用it迭代器会安全一点. 这是c+ ...

  5. IOS UIActivityIndicatorView动画

    ● 是一个旋转进度轮,可以用来告知用户有一个操作正在进行中,一般 用initWithActivityIndicatorStyle初始化 ● 方法解析: ● - (void)startAnimating ...

  6. .net reflector 的缺陷

    .net reflector是一个反编译DLL的工具,在安装后如果电脑上有VS也会同时安装到VS里面,但是他是收费的,虽然反编译的效果很好,但是运行VS2013时(或许其他版本也有这样的问题)如果项目 ...

  7. Android(java)学习笔记98:如何让你的GridView不再滚动

    1. 如何让你的GridView不再滚动: GridView显示不完整的原因是因为,他的外层也套用了一个滑动的控件,这个解决办法是:重写GridView,是控制GridView不能滚动,就是写一个类继 ...

  8. Android(java)学习笔记90:TextView 添加超链接(两种实现方式)

    1. TextView添加超链接: TextView添加超链接有两种方式,它们有区别于WebView: (1)方式1: LinearLayout layout = new LinearLayout(t ...

  9. python_44_文件属性

    #打印文件属性信息 import os#os.stat()返回的文件属性元组元素的含义 filestats=os.stat('yesterday')#获取文件/目录的状态 print(filestat ...

  10. Nodejs:Node.js模块机制小结

    今天读了<深入浅出Nodejs>的第二章:模块机制.现在做一个简单的小结. 序:模块机制大致从这几个部分来讲:JS模块机制的由来.CommonJS AMD CMD.Node模块机制和包和n ...