3Sum Closest My Submissions Question Editorial Solution Total accepted:76085 Total submissions:261853 Difficulty:medium
Given an array S of n integers, find three integers in S such, the sum was closest to a Given number, target. Return the sum of the three integers. You may assume this each input would has 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).
Subscribe to see which companies asked this question show Tags show Similar problems
The topic's approximate meaning is: Given an array of nums and an integer target, find three numbers from the array, make them closest to target, and return this and value.
The difficulty level of the problem: medium
Ideas:
1, similar to the topic 3Sum , is the first to sort the array, and then enumeration and clamping force, with Minsum to record the nearest target value;
2 , from left to right enumeration, the enumeration position is I (0<i<nums.size ()), left and right respectively with L,R to represent, and l<i ,R>i, from both sides to the middle clamp (the middle refers to the enumeration position);
3, Tmp=nums[l]+nums[i]+nums[r], if abs (Tmp-target) < (Minsum-target), explain to find a closer, to record down. And, if tmp>target, then the description and value is large, at this time --r; if tmp<target, the description and value is small, then ++l; if tmp== Target, which means to find a unbiased, return directly.
The code is as follows:
Class Solution {public
:
int threesumclosest (vector<int>& nums, int target) {
sort (nums.begin ( ), Nums.end ());
int minsum = 99999999;
int L, R, TMP;
for (int i = 1; i < Nums.size ()-1; ++i) {
L = 0;r = Nums.size ()-1;
while (L < i && r > i) {
tmp = Nums[l] + nums[i] + nums[r];
if (TMP = = target) {return target;}
(tmp > Target)? (--r): (++l);
if (ABS (Minsum-target) > abs (tmp-target)) {
minsum = tmp;
}}} return minsum;
}
;
After the code has been submitted, smooth
ACDrop the question,
Runtime:12 Ms。
There is another way to AC The problem, of course, the same as above, but in the pinch, it is from the middle to both sides of the divergence.
The code is as follows:
Class Solution {public
:
int threesumclosest (vector<int>& nums, int target) {
sort (nums.begin () , Nums.end ());
int minsum = 99999999;
int L, R, TMP;
for (int i = 1; i < Nums.size ()-1; ++i) {
L = i-1;
R = i + 1;
while (l >= 0 && R < nums.size ()) {
TMP = Nums[l] + nums[i] + nums[r];
if (TMP = = target) {return target;}
(tmp > Target)? (--l): ++r;
if (ABS (Tmp-target) < ABS (Minsum-target)) {
minsum = tmp;
}}} return minsum;
}
;
runtime:16 Ms