【LeetCode】16. 3Sum Closest

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

 

第一重循环先确定第一个数字,

然后第二重循环用双指针分别从两端遍历,使得三个数的和不断接近target。

若三个数的和等于target,则可以立即返回。

时间复杂度:O(n2)

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

posted @ 2014-12-21 12:16  陆草纯  阅读(196)  评论(0编辑  收藏  举报