【3Sum Closest 】cpp
题目:
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的更多相关文章
- hdu 4739【位运算】.cpp
题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...
- 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~ ...
- 【Valid Sudoku】cpp
题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...
- 【Permutations II】cpp
题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...
- 【Subsets II】cpp
题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...
- 【Sort Colors】cpp
题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...
- 【Sort List】cpp
题目: Sort a linked list in O(n log n) time using constant space complexity. 代码: /** * Definition for ...
- 【Path Sum】cpp
题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...
- 【Symmetric Tree】cpp
题目: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). F ...
随机推荐
- fish 与oh-my-fish 的安装
fish 相对于 自带的shell优势很大,最近在研究使用中. 安装教程如下: sudo apt-get install fish oh-my-fish是github上开源项目,使得fish的使用更加 ...
- silverlight数据绑定模式TwoWay,OneWay,OneTime的研究
asp.net开发中,数据绑定是一个很简单的概念,控件与数据绑定后,控件可以自动把数据按一定的形式显示出来.(当然控件上的值改变后,可以通过提交页面表单,同时后台服务端代码接收新值更新数据) silv ...
- iOS JS 交互之利用系统JSContext实现 JS调用OC方法以及Objective-C调用JavaScript方法
ios js 交互分为两块: 1.oc调用js 这一块实现起来比较简单, 我的项目中加载的是本地的html,js,css,需要注意的是当你向工程中拖入这些文件时,选择拷贝到工程中,(拖入的文件夹是蓝色 ...
- SQL重复记录查询-count与group by having结合查询重复记录
查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断select * from peoplewhere peopleId in (select peopleId from p ...
- vue指令总结(二)
一.vue指令 1.v-text v-text是用于操作纯文本,它会替代显示对应的数据对象上的值.当绑定的数据对象上的值发生改变,插值处的内容也会随之更新.注意:此处为单向绑定,数据对象上的值改变,插 ...
- linux 命令——34 du(转)
Linux du命令也是查看使用空间的,但是与df命令不同的是Linux du命令是对文件和目录磁盘使用的空间的查看,还是和df命令有一些区别的. 1.命令格式: du [选项][文件] 2.命令功能 ...
- xtarbackup恢复
xbstream -x < ynhw-mysql-slave.01.mysql.prod.sg_fullbak_20180326134255.xbstream -C /data/mysql cd ...
- 【洛谷1993】小K的农场(差分约束系统模板题)
点此看题面 大致题意: 给你若干组不等式,请你判断它们是否有解. 差分约束系统 看到若干组不等式,应该很容易想到差分约束系统吧. \(A-B≥C\):转换可得\(A-B≥C\) \(A-B≤C\):转 ...
- 简析平衡树(二)——Treap
前言 学完了替罪羊树,我决定再去学一学\(Treap\).一直听说\(Treap\)很难,我也花了挺久才学会. 简介 \(Treap\)这个名字真的挺有内涵: \(\color{red}{Tree}\ ...
- HTML第四章:初始css
CSS样式: 一.为什么要使用CSS;可以让页面更美观.有利于开发速度. 二.什么是CSS:全称cascading style shee ...