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类似,只需添加判断是否是最近的即可。
代码:
 1     int threeSumClosest(vector<int> &num, int target) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         int cur = INT_MAX, res;
 5         int len = num.size();
 6         int i,j,k;
 7         sort(num.begin(), num.end());
 8         for(i = 0; i < len-2; i++){
 9             while(i > 0 && num[i] == num[i-1])
10                 i++;
11             j = i+1;
12             k = len - 1;
13             while(j < k){
14                 int t = num[i]+num[j]+num[k];
15                 if(t<target)
16                     j++;
17                 else if(t>target)
18                     k--;
19                 else{
20                     return target;
21                 }
22                 if(abs(t-target) < cur){
23                     cur = abs(t-target);
24                     res = t;
25                 }
26             }
27         }
28         return res;
29     }
原文地址:https://www.cnblogs.com/waruzhi/p/3413240.html