16. 3Sum Closest
2015-06-05 10:14
375 查看
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.
与2sum,3sum类似
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).
与2sum,3sum类似
//http://www.cnblogs.com/remlostime/archive/2012/10/27/2742667.html class Solution { public: int threeSumClosest(vector<int> &num, int target) { sort(num.begin(), num.end()); int ret; bool first = true; for(int i = 0; i < num.size(); i++) { int j = i + 1; int k = num.size() - 1; while(j < k) { int sum = num[i] + num[j] + num[k]; //如果是第一次,先求出一个和在ret中保存下来至 if (first) { ret = sum; first = false; } //否则,将该次循环产生的(和-target)与(ret-target进行比较) else {//如果该次循环的差值更小,则更新ret if (abs(sum - target) < abs(ret - target)) ret = sum; } if (ret == target) return ret; if (sum > target) k--; else j++; } } return ret; } };
相关文章推荐
- IOS开发系列--学习资料整理
- Java NIO系列教程(九) ServerSocketChannel
- eclipse ADT
- Ckeditor通过Ajax更新数据
- fragment添加menu 以及 fragment中调用onActivityResult
- CSUOJ 1635 Restaurant Ratings
- Mysql慢查询配置
- 电脑怎样去除任务栏获取windows10图标?
- PS 图像黑白调整算法(彩色图转灰度图)(VC++)
- Codeforces Round #306 div 2 solution
- 下拉列表框
- 【转】数据库SQL的一些总结
- 资源版本比较
- fopen vs fsocketopen vs curl
- Openssl 制作CA证书简易方法
- Openssl 制作CA证书简易方法
- 5月末周全球域名注册商(国际域名)新增注册量TOP12
- JAVA 对象数组按照多个属性进行排序
- python实现数值积分的Simpson方法实例分析
- visibilitychange事件判断当前页面——可见性的状态