Original title:
Given an array S of n integers, find three integers in s such so the sum is closest to a Given number, target. Return the sum of the three integers. You may assume this each input would have exactly one solution.
For example, given array S = {-1 2 1-4}, and target = 1.
The sum is closest to the target is 2. (-1 + 2 + 1 = 2).
The analysis:
And the 3sum similar to the question number 15, but this problem requires three numbers and is a given number, that is, find a+b+c=target, solve the same ideas, the two number of the sum of the target into target-a can.
Problem-Solving Code:
For example, given array S = {-1 2 1-4}, and target = 1. The sum is closest to the target is 2.
(-1 + 2 + 1 = 2). Finds three digits from the given array, which is closest to the given target #include <iostream> #include <vector> #include <algorithm> using
namespace Std; Class Solution {public:int threesumclosest (vector<int>& nums, int target) {if (Nums.size () <3) {RE
turn-1;
int tarsum = 0;
int tempsum = 0;
int nmin = 1024;
int nret = 0; Sort (Nums.begin (), Nums.end ()); Causes the number in the container to be an ordered sequence for (int i=0; I<nums.size ()-2; i++) {tarsum = target-nums[i];//Declare the target of the search and A+b+c = targets, a+b = target-c int j = i+1;
Declares the search for the end-node int k=nums.size ()-1;
while (j<k) {tempsum = Nums[j]+nums[k]-tarsum;
if (ABS (TempSum) < nmin) {nmin = ABS (TempSum);
Nret = Nums[i]+nums[j]+nums[k];
} if (TempSum < 0) {j + +;
else if (TempSum > 0) {k--; else if (tempsum = 0) {return TARget;
}} return nret;
}
};