16.3Sum Closest (Two-Pointers)

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>& nums, int target) {

        int size = nums.size();

        

        sort(nums.begin(), nums.end());

        diff = INT_MAX;

        for(int i = 0; i < size-2; i++){

            if(i>0 && nums[i]==nums[i-1])  continue;

            find(nums, i+1, size-1, target-nums[i]);

            if(diff == 0) return target;

        }

        return target+diff;

    }

    

      void find(vector<int>& nums, int start, int end, int target){

        int sum;

        while(start<end){

            sum = nums[start]+nums[end];

            if(sum == target){

                diff = 0;

                return;

            }

            else if(sum>target){

                do{

                    end--;

                }while(end!=start && nums[end] == nums[end+1]);

                if(sum-target < abs(diff)) diff = sum - target;

            }

            else{

                do{

                    start++;

                }while(start!= end && nums[start] == nums[start-1]);

                if(target - sum < abs(diff)) diff = sum - target; //不能只在最后检查:可能会有这种情况,前一次sum>target,这次sum<target,而且下次就start==end,那么很可能前一次的sum比这次的sum更接近target

            }

        }

    }

private:

    int diff; //how much bigger is the sum

};

 

你可能感兴趣的:(close)