[leetcode] 3Sum Closest
2014-04-26 11:28
337 查看
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类似,但并不是列出所有和为0的三元组,而是找出与target最相近的sum,同样是利用三个指针i,p和q,具体请参考3Sum。只不过在遍历时记录最小误差minerror,最后返回target+minerror即可。
代码如下:
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类似,但并不是列出所有和为0的三元组,而是找出与target最相近的sum,同样是利用三个指针i,p和q,具体请参考3Sum。只不过在遍历时记录最小误差minerror,最后返回target+minerror即可。
代码如下:
class Solution { public: int threeSumClosest(vector<int> &num, int target) { sort(num.begin(), num.end()); int minerror = num[0]+num[1]+num[2] - target; for( int i = 0 ; i < num.size() ; i++ ) { if( i > 0 && num[i] == num[i-1] ) { continue; } int p = i+1; int q = num.size() - 1; while( p < q ) { if( p > i +1 && num[p] == num[p-1] ) { p++; continue; } if( q < num.size() -1 && num[q] == num[q+1] ) { q--; continue; } int sum = num[i] + num[p] + num[q]; if( abs(sum - target) < abs(minerror) ) { minerror = sum - target; } if( sum - target == 0) { return target; } if( sum - target > 0 ) { q--; } if( sum - target < 0 ) { p++; } } } return minerror + target; } };
相关文章推荐
- [leetcode 16] 3Sum Closest
- leetcode---3Sum Closest
- [leetcode] 3Sum Closest
- LeetCode 解题报告 3Sum Closest
- leetcode: 16. 3Sum Closest
- Leetcode016 3Sum Closest
- [LeetCode][JavaScript]3Sum Closest
- [LeetCode] 3Sum Closest
- 【LeetCode】3Sum Closest
- LeetCode 016 3Sum Closest
- Leetcode习题记录——3Sum Closest
- 【Leetcode】3Sum Closest
- LeetCode 遍历技巧 | 16. 3Sum Closest
- Leetcode || 3Sum Closest
- 【leetcode刷题笔记】3Sum Closest
- LeetCode 3Sum Closest
- 《leetCode》:3Sum Closest
- LeetCode - 3Sum Closest
- python写算法题:leetcode: 16. 3Sum Closest
- LeetCode——16. 3Sum Closest