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

思路:这道题就是从一个数组中找到三个数的和与目标值最接近的值,然后返回。一般先对这个数组排序,时间复杂度在O(nlogn),然后在对这个排序后的数组处理,首先从头开始枚举一个数,然后再找出其后一个元素与最后一个元素,他们三个的数之和与目标值的差值,作为判断的依据,如果差值最小,则更新这个最小差值,如果这个差值大于0,则最后一个向前移动,相反,第二个向后移动。如此反复,就可以得出想要的目标值。
class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int nSize=num.size();
        if(nSize<3)
            return 0;
        sort(num.begin(),num.end());
        int diff=0;
        int min_diff=num[0]+num[1]+num[2]-target;
        for(int i=0;i<=nSize-3;i++)
        {
            int j=i+1;
            int k=nSize-1;
            while(j<k)
            {
                diff=num[i]+num[j]+num[k]-target;
                if(diff==0)
                    return target;
                if(abs(diff)<abs(min_diff))
                    min_diff=diff;
                if(diff<0)
                    j++;
                else
                    k--;
            }
        }
        return target+min_diff;
    }
};

 

 
posted @ 2014-04-20 23:58  Awy  阅读(169)  评论(0编辑  收藏  举报