LeetCode: 3SumClosest

Title :

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).
int threeSumClosest(vector<int> &num, int target){
        sort(num.begin(),num.end());
        int min = INT_MAX;
        int result;
        for (int i = 0 ; i < num.size()-2; i++){
            if (i > 0 && num[i] == num[i-1])
                continue;
            int left = i+1;
            int right = num.size()-1;
            int goal = target - num[i];
            while (left < right){
                int diff = abs(target - num[left] - num[right] - num[i]);
                if (diff < min){
                    min = diff;
                    result = num[left] + num[right] + num[i];
                }
                if (num[left] + num[right] < goal){
                    while (left < right && (num[left] == num[left+1]))
                        left++;
                    left++;
                }else if (num[left] + num[right] > goal){
                    while (left < right && (num[right] == num[right-1]))
                        right--;
                    right--;
                }else{
                    return target;
                }
            }
        }
        return result;
    }
原文地址:https://www.cnblogs.com/yxzfscg/p/4419369.html