【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 ...
随机推荐
- MATLAB之折线图、柱状图、饼图以及常用绘图技巧
MATLAB之折线图.柱状图.饼图以及常用绘图技巧 一.折线图 参考代码: %图1:各模式直接成本预测 %table0-table1为1*9的数组,记录关键数据 table0 = data_modol ...
- git学习(一)
提: 远程的主机名(远程仓库服务器名): origin 本地的主分支: master(本地master分支) 远程的主分支: maste(远程仓库的master分支) gi ...
- 使用adbWireless无线调试Android真机设备[转]
开发Android的朋友都知道,真机调试需要把手机与PC相连,然后把应用部署到真机上进行安装和调试.长长的USB线显得很麻烦,而且如果需要USB接口与其他设备连接的话显得很不方便.今天介绍一种不通过U ...
- TP5.0:同一个控制器访问不同方法
首先,我把TP框架的内容放置在manualtp5文件夹 在manualtp5/application/index/controller/index控制器中定义两个方法: 我们都知道,如果我们网址中不输 ...
- 最好的 6 个 HTML5 的多媒体播放器
是 HTML5 中新引入的标签,用来在 Web 网页中嵌入视频播放功能,无需 Flash 和其他嵌入式插件的支持,是浏览器内建的功能,不过 旨在一些高级浏览器中支持,例如 Firefox, Sa ...
- EF写统计
EF的特性是,你from的第一个表为主表,接下来的所有表以左联或者内联或者交叉连接的方式去显示,不会出现右联, 在编写的时候,可以先确定个数据源,然后对这个数据源进行数据的统计, 例如SQL: -- ...
- 爬虫爬取代理IP池及代理IP的验证
最近项目内容需要引入代理IP去爬取内容. 为了项目持续运行,需要不断构造.维护.验证代理IP. 为了绕过服务端对IP 和 频率的限制,为了阻止服务端获取真正的主机IP. 一.服务器如何获取客户端IP ...
- 在RichTextBox控件中添加超链接文本
实现效果: 知识运用: RichTextBox控件的AppendText方法 public void AppendText{string textData} //向控件中添加文本内容 和Process ...
- 漫谈 Clustering (番外篇): Dimensionality Reduction
由于总是有各种各样的杂事,这个系列的文章竟然一下子拖了好几个月,(实际上其他的日志我也写得比较少),现在决定还是先把这篇降维的日志写完.我甚至都以及忘记了在这个系列中之前有没有讲过“特征”(featu ...
- H1ctf-Vote
用来练习IO_FILE利用 glibc-2.23 # coding:utf-8 from pwn import * from FILE import * context.arch = 'amd64' ...