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).

 

Subscribe to see which companies asked this question

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int min = 999999;
        int size = num.size();
        sort(num.begin(), num.end());
        for (int i=0; i<size-2; i++)
        {
           if (i>0 && num[i] == num[i-1]) {
               continue;
           }
           int j = i+1;
           int k = size - 1;
           while (j<k)
           {
               int tmp = num[i]+num[j]+num[k];
               if (tmp - target == 0)
                    return tmp;
               else if (tmp - target < 0)
               {
                   if (abs(tmp-target) < abs(min-target))
                    {
                        min = tmp;
                    }
                    j++;
                    while (num[j-1] == num[j]) {
                        j++;
                    }
                    
               }
               else
               {
                    if (abs(tmp-target) < abs(min-target))
                    {
                        min = tmp;
                    }
                    k--;
                    while (num[k] == num[k+1]) {
                        k--;
                    }
               }
               
           }
        }
        return min;
    }
};

 

posted on 2016-01-04 23:49  walkwalkwalk  阅读(224)  评论(0编辑  收藏  举报

导航