[leetcode] 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类似,但并不是列出所有和为0的三元组,而是找出与target最相近的sum,同样是利用三个指针i,p和q,具体请参考3Sum。只不过在遍历时记录最小误差minerror,最后返回target+minerror即可。
代码如下:
1 class Solution { 2 public: 3 int threeSumClosest(vector<int> &num, int target) 4 { 5 sort(num.begin(), num.end()); 6 int minerror = num[0]+num[1]+num[2] - target; 7 for( int i = 0 ; i < num.size() ; i++ ) 8 { 9 if( i > 0 && num[i] == num[i-1] ) 10 { 11 continue; 12 } 13 int p = i+1; 14 int q = num.size() - 1; 15 while( p < q ) 16 { 17 if( p > i +1 && num[p] == num[p-1] ) 18 { 19 p++; 20 continue; 21 } 22 23 if( q < num.size() -1 && num[q] == num[q+1] ) 24 { 25 q--; 26 continue; 27 } 28 29 int sum = num[i] + num[p] + num[q]; 30 31 if( abs(sum - target) < abs(minerror) ) 32 { 33 minerror = sum - target; 34 } 35 36 if( sum - target == 0) 37 { 38 return target; 39 } 40 41 if( sum - target > 0 ) 42 { 43 q--; 44 } 45 46 if( sum - target < 0 ) 47 { 48 p++; 49 } 50 } 51 } 52 return minerror + target; 53 } 54 };