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
- 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;
}
};