LeetCode16:3Sum Closest
2015-11-06 21:39
204 查看
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.
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).
#include<iostream> #include<algorithm> #include<vector> using namespace std; //要求3个数的和最接近target,所以我们先固定其中1个数,再用求“和为某值的2个数的组合”的解法,就能把剩下的2个数求出 //来。因此,先对数组进行非递减排序,这样整个数组的数就由小到大排列。i 的取值由 0 至 n - 1,对每一个i,我们求当num[i]是解当 //中的其中一个数时,其他的2个数。设有指针p指向数组头(实际只要p从i + 1开始),q指向数组尾,cur = num[i] + num[p] + num[q],那 //么当前值与所求值target之间的差距就为temp = cur - target,如果abs(temp) < min,更新min = abs(temp)和当前解res = cur。 //现在分为3种情况: //1. temp == 0,说明与target最接近,因为题目已经说明只有一个解,所以直接返回cur; //2. temp < 0,说明num[p]太小了,将p向后移动一个位置; //3. temp > 0,说明num[q]太大了,将q向前移动一个位置。 //如此循环直到p == q为止。 class Solution { public: int threeSumClosest(vector<int> &num, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. //如果数组元素个数num.size() == 3,直接返回这3个数的和,因为只有这个解; if (num.size() == 3) return num[0] + num[1] + num[2]; //非递减(递增)排序 sort(num.begin(), num.end()); int min = 0x7fffffff; int res = 0; int cur = 0; for (int i = 0; i < num.size(); ++i) { //刚才找过了同值的,直接跳过 if (i != 0 && num[i] == num[i - 1]) continue; int p = i + 1, q = num.size() - 1; // p可以直接从i + 1位置开始,因为在i 之前的位置j 上的数如果也是解的一部分,那么在求j的时候,肯定把i位置上的数也算过了; while (p < q) { cur = num[i] + num[p] + num[q]; int temp = cur - target; if (temp == 0) //刚好相等直接返回 return cur; if (abs(temp) < min) //更新值 { min = abs(temp); res = cur; } //移动指针进行下一步操作 ,注意在移动p和q的时候,不能等于i if (temp < 0) { while (++p < q && p == i) { //do nothing } } else //temp > 0 { while (--q > p && q == i) { //do nothing } } } } return res; } }; int main() { vector<int> num1 = { -1, 2, 1,-4 }; Solution sol; int t = sol.threeSumClosest(num1, 1); cout << t << endl; system("pause"); return 0; }
相关文章推荐
- Android中的webview详细使用
- 大端小端的判断
- 去掉 WordPress 3.1+版本顶部的admin bar管理工具
- Linux时间函数
- 为什么有logistics函数
- Matlab “Out of memory”解决办法
- Libev源码分析06:异步信号同步化--sigwait、sigwaitinfo、sigtimedwait和signalfd
- hdu 4664 Triangulation(博弈)
- 地理位置查询附近商家
- adb常用命令
- ecshop中smarty最常用的6大基本语法
- 深入浅出 React Native:使用 JavaScript 构建原生应用
- 操作系统与网络实现 之七
- c++虚函数
- 指针、数组
- Course Schedule
- hdu 4662 MU Puzzle(水)
- Android如何获取asset目录下所有文件的路径
- 汇编语言 用户名密码登录验证程序 (dos调用)
- 愤怒的小鸟-物理世界Box2d(1)-静态刚体的创建