题目

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. Hibernate数据库的操作

    参考网址: https://www.cnblogs.com/jack1995/p/6952704.html 1.最简单的查询 List<Special> specials = (List& ...

  2. Jscript 命名规范

    变量命名都以类型前缀+有意义的单词组成,用驼峰式命名法增加变量和函式的可读性.例如:sUserName,nCount. 前缀规范:每个局部变量都需要有一个类型前缀,按照类型可以分为:s:表示字符串.例 ...

  3. Python __builtin__模块

    你有没有好奇过当我们打开Python后就可以直接使用str(),list(),eval(),print(),max()这样的函数,而不用导入任何模块? 其实原因很简单,就是当我们打开Python解释器 ...

  4. php使用GD库实现图片水印和缩略图——生成图片缩略图

    今天呢,就来学习一下在php中使用PD库来实现对图片水印的文字水印方法,不需要PS哦! 首先,准备素材 (1)准备一张图片 (2)准备一张水印(最好是透明的,即背景是白色底) (3)准备一中字体(在电 ...

  5. c++指针二维数组

    ; int** G; //初始化 G = new int*[N]; ; i < N; i++) G[i] = new int[N]: //删除 ; i < N; i++) delete[] ...

  6. Count Numbers(矩阵快速幂)

    Count Numbers 时间限制: 8 Sec  内存限制: 128 MB提交: 43  解决: 19[提交] [状态] [讨论版] [命题人:admin] 题目描述 Now Alice want ...

  7. 2018.5.24 Oracle下的sqlplus编程 块结构

    1.语句结构模板 declare --声明 begin dbms_output.put_line('Legend Hello world'); end; 2.变量使用 & 是输入符号 decl ...

  8. Angular2的笔记

    1.如果启动项目的时候出现下列黄色的警告说明电脑安装的全局cli和项目中使用的cli版本不一致,不过不影响使用,按它的提示执行 ng set --global warnings.versionMism ...

  9. XML字符串解析

    不多说,直接上代码: import java.io.StringReader; import org.dom4j.Document; import org.dom4j.DocumentExceptio ...

  10. 深入理解java虚拟机读书笔记1--java内存区域

    Java在执行Java程序的过程中会把它所管理的内存划分为若干个不同的数据区域.这些区域都有各自的用途.创建和销毁的时间,有一些是随虚拟机的启动而创建,随虚拟机的退出而销毁,有些则是与线程一一对应,随 ...