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


class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) 
    {
        for(int i=0;i<num.size();i++)
            for(int j=i+1;j<num.size();j++)
                if(num[i]>num[j])
                {
                    int tmp=num[i];
                    num[i]=num[j];
                    num[j]=tmp;
                }
        int size=num.size();
        if(size<3return 0;
        
        int close=num[0]+num[1]+num[2];
        for(int index1=0;index1<size-2;index1++)
        {
            int index2=index1+1;
            int index3=size-1;
            while(index2<index3)
            {
                int sum=num[index1]+num[index2]+num[index3];
                if(abs(close-target)>abs(sum-target))
                    close=sum;
                if(sum<target) index2++;
                else index3--;
            }
        }
        return close;
    }
    int abs(int a)
    {
        return a>=0?a:-a;
    }
};
posted @ 2014-05-29 15:32  erictanghu  阅读(115)  评论(0编辑  收藏  举报