【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 ...
随机推荐
- HTTPS与SSL(一)
1. HTTPS HTTPS(全称:Hypertext Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HTTP的安全版 ...
- 使用HTML5 canvas做地图(1)基础知识
之前一直想使用HTML5技术全新做一套地图API,可是苦于时间和精力,迟迟未有行动.后来下定决心,利用下班和周末做出一个大体框架出来,现在和网友分享一下自己的整体的一个思路和想法.欢迎大家提出宝贵建议 ...
- python基础-数据运算
*按位取反运算规则(按位取反再加1) 详解http://blog.csdn.net/wenxinwukui234/article/details/42119265 详细内容ht ...
- vs移动团队项目集合
vs移动团队项目集合: https://msdn.microsoft.com/zh-cn/library/vs/alm/dd936138(v=vs.120)/css
- ASP.NET中登陆验证码的生成和输入验证码的验证
一:验证码的生成实现代码 protected void Page_Load(object sender, EventArgs e) { string validateCode = ...
- BZOJ 4128: Matrix
BZOJ 4128: Matrix 标签(空格分隔): OI BZOJ 大步小步 矩阵 费马小定理 Time Limit: 10 Sec Memory Limit: 128 MB Descriptio ...
- 在C++类中使用dllimport和dllexport导出,
在Windows平台下: 您可以使用dllimport或dllexport属性声明C ++类.这些形式意味着导入或导出整个类.以这种方式导出的类称为可导出类. 以下示例定义可导出的类.导出其所有成员函 ...
- CUDA开发:了解设备属性
原文链接 今天介绍一下CUDA设备的相关属性,只有熟悉了硬件是相关属性,是怎么工作的,就能写出更适合硬件工作的代码.cudaDeviceProp这个结构体记录了设备的相关属性. struct cuda ...
- js当中mouseover和mouseout多次触发(非冒泡)
JS当中,mouseover和mouseout多次触发事件,不光是冒泡会产生,就是不冒泡,在一定条件下 ,也会产生多次触发事件: 例如下面的结构的情况下,我在class="ceng_up f ...
- C的xml编程-libxml2
这里主要讲述libxml2在linux下的使用. (以下内容除了linux下的安装步骤是自己写的,其余均出自http://www.blogjava.net/wxb_nudt/archive/2007/ ...