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双指针的做法,做起来会比较麻烦。
class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        sort(num.begin(),num.end());
        int min = -1;
        int re = 0;
        for(int i = 0 ; i < num.size()-2;i++)
        {
            int tar =target - num[i];
            int left = i+1,right = num.size()-1;
            while(left < right)
            {
                int now = abs(tar - num[left] -num[right]);
                if(min<0) 
                {
                    min = now;
                    re = num[i] + num[left] + num[right];
                }
                
                if(now < min) {min = now;re = num[i] + num[left] + num[right];}
                
                if(tar > num[left] + num[right]) left++;
                else if((tar < num[left] + num[right])) right --;
                else
                return target;
            }
        }
        return re;
    }
};

 

posted on 2014-03-07 11:03  pengyu2003  阅读(126)  评论(0编辑  收藏  举报

导航