3Sum Closest

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).
 
与 3Sum类似,只是需要添加一个变量distance,用来记录和target距离最小的a+b+c
 
 class Solution {
public:
int threeSumClosest(vector<int> &num, int target) { int n=num.size();
sort(num.begin(),num.end()); int i,j,k;
int a,b,c;
int result;
int distance=INT_MAX; for(i=;i<n-;i++)
{
j=i+;
k=n-; while(j<k)
{
a=num[i];
if(i>&&num[i]==num[i-])
{
break;
}
b=num[j];
if(j>i+&&num[j]==num[j-])
{
j++;
continue;
} c=num[k];
if(k<n-&&num[k]==num[k+])
{
k--;
continue;
} if(a+b+c==target)
{
return target;
}
else if(a+b+c<target)
{
if(target-(a+b+c)<distance)
{
result=a+b+c;
distance=target-result;
}
j++;
}
else if(a+b+c>target)
{
if((a+b+c)-target<distance)
{
result=a+b+c;
distance=result-target;
}
k--;
}
}
} return result; }
};

最新文章

  1. 关于领域驱动设计(DDD)中聚合设计的一些思考
  2. Hibernate 系列 01 - 框架技术 (介绍Hibernate框架的发展由来)
  3. [leetcode 27]Implement strStr()
  4. Android自定义ScrollView分段加载大文本数据到TextView
  5. Android源码网站
  6. shape和selector的结合
  7. iOS 将图片保存到本地
  8. sql之left join、right join、inner join的区别(转)
  9. .NET技能分析
  10. LeetCode解题报告:Binary Tree Postorder Traversal
  11. 69、django之Form组件
  12. jeecg入门操作—字典配置
  13. 4.SSM整合_多表_多对多的增删改查
  14. 动态 DP 学习笔记
  15. dom4j string转为xml
  16. mergesort_arithmetic_python
  17. Python Socket函数及说明
  18. 用Javascript 实现倒计时
  19. ubuntu Mono+Jexus 部署到 ASP.NET MVC 5
  20. 读书笔记5基于matplotlib画图

热门文章

  1. HTML5的拖拽时间 ondragstart
  2. 【HDU 5438】Ponds
  3. Yii2提示信息设置方法
  4. 【转】set容器的基本操作
  5. 洛谷P1993 小 K 的农场
  6. Bsoj 1322 第K小数
  7. Linux VPS新硬盘分区与挂载教程
  8. linux环境下安装sphinx中文支持分词搜索(coreseek+mmseg)
  9. Idea 添加lib文件夹,并添加至项目Libary
  10. python多线程备份MYSQL数据库并删除旧的备份。