[leetcode 16] 3Sum Closest
来源:互联网 发布:linux telent 安装 编辑:程序博客网 时间:2024/05/21 10:11
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, 排序之后,夹逼
class Solution {public: int threeSumClosest(vector<int> &num, int target) { int res; if (num.size() < 3) { return res; } int min_gap = INT_MAX; //记录最小的差值 sort(num.begin(), num.end()); auto last = num.end(); for (auto i = num.begin(); i < last - 2; i++) { auto j = i + 1; auto k = last - 1; while (j < k) { int sum = *i + *j + *k; int gap = abs(sum - target); if (gap < min_gap) { res = sum; min_gap = gap; } if (sum > target) { k--; } else { j++; } } } return res; }};
0 0
- LeetCode 16: 3Sum Closest
- LeetCode 16: 3Sum Closest
- leetcode 16 3Sum Closest
- [leetcode 16] 3Sum Closest
- Leetcode【16】:3Sum Closest
- [leetcode 16] 3Sum Closest
- [Leetcode] 16 - 3Sum Closest
- leetcode.16----------3Sum Closest
- leetcode 16 3Sum Closest
- leetcode-16 3Sum closest
- LeetCode---(16) 3 Sum Closest
- LeetCode 16 - 3Sum Closest
- leetcode 16 -- 3Sum Closest
- 3Sum Closest - LeetCode 16
- leetcode 16: 3Sum Closest
- Leetcode#16 3Sum Closest
- LeetCode(16) 3Sum Closest
- LeetCode #16 3Sum Closest
- C++/CLI 托管C++的数组介绍【4】
- c#如何esc退出Form
- 常见算法学习(C语言实现)(一)
- Sort Colors
- codeforces good bye 2014
- [leetcode 16] 3Sum Closest
- python解压缩zip文件
- hadoop 之初接触
- 蛇形矩阵for循环实现
- 2014 年终总结...
- 关于QMessageBox中按键位置的调换
- hdu_1878_欧拉回路_并查集
- 1.SqlDataAdapter操作sql2012
- BNF(巴科斯-瑙尔范式)和EBNF(扩展巴科斯-瑙尔范式)