Given an array of n integers nums and a target value target. Find the three integers in the nums so that they are closest to target. Returns the and of these three numbers. Assume that there is only one answer for each set of inputs.
For example, given an array nums = [ -1,2,1,-4], and target = 1.
The number of the closest three to target is 2. (-1 + 2 + 1 = 2).
The topic and the previous question Leetcode 15. Three number and the https://blog.csdn.net/u011750466/article/details/80218002 solution mentality is same, the procedure slightly changes.
1. Go to republication
Class Solution {public:int threesumclosest (vector<int>& nums, int target) {sort (Nums.begin (), Nums
. end ()); The question for int sum=0,close=int_max,m=0,result=0;//conversion to two numbers for (int i=0;i<nums.size () -2;++i) {M=target-nums[i
];
int l=i+1,r=nums.size () -1;//double pointer method while (L<R) {sum=nums[l]+nums[r];
if (sum<m) {if (m-sum<close) {close=m-sum;
RESULT=NUMS[I]+NUMS[L]+NUMS[R];
} ++l;
while (L<r&&nums[l]==nums[l-1]) ++l;//to heavy} else if (sum>m) {
if (sum-m<close) {close=sum-m;
RESULT=NUMS[I]+NUMS[L]+NUMS[R];
}--r; while (L<r&&nums[r]==nums[r+1])--r;//to heavy} else retUrn target;//If equality is returned directly} while (I<nums.size () -2&&nums[i]==nums[i+1]) ++i;//to heavy}
return result; }
};
2. Do not go to republication
Class Solution {public
:
int threesumclosest (vector<int>& nums, int target) {
sort (nums.begin () , Nums.end ());
int sum=0,close=int_max,m=0,result=0;
for (int i=0;i<nums.size () -2;++i) {
m=target-nums[i];
int L=i+1,r=nums.size ()-1;
while (l<r) {
sum=nums[l]+nums[r];
if (sum<m) {
if (m-sum<close) {
close=m-sum;
RESULT=NUMS[I]+NUMS[L]+NUMS[R];
}
++l;
}
else if (sum>m) {
if (sum-m<close) {
close=sum-m;
RESULT=NUMS[I]+NUMS[L]+NUMS[R];
}
--r;
}
else{return
target;
}
}
return result;
}
;