The closest Leetcode ter and the number of

Title Description

Given an array comprising n integers and a target nums target. Nums identify the three integers, and a target such that their closest. The three numbers and return. Each group assumes that there is only input the only answer.

Thinking

  1. And the number of ideas with three similar, but a plus error is determined, the minimum error return

Code

method one:

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        if(nums.size()==0)
            return 0;
        if(nums.size()==1)
            return nums[0];
        sort(nums.begin(),nums.end());
        int res = INT_MAX;
        for(int i = 0; i < nums.size()-2;i++)
        {
            int error = TwoSumClosest(nums,i,target);
            if (abs(error)<abs(res))
			    res = error;
        }
        return target+res;
    }
    int TwoSumClosest(vector<int>& nums,int i, int target)
    {
        target = target - nums[i];
        int left = i + 1, right = nums.size()-1;
        int error = INT_MAX;
        while(left<right)
        {
            int sum = nums[left] + nums [right];
            if (abs(sum - target)<abs(error))
                error = sum - target;
            if(sum < target)
                left++;
            else if(sum > target)
                right--;
            else
                return 0;
        }
        return error;
    }
};
Published 85 original articles · won praise 0 · Views 370

Guess you like

Origin blog.csdn.net/weixin_38312163/article/details/105078396