Leetcode Note: 3Sum Closest
I. Description
Ii. problem-solving skills <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Release/release + lB1tC1xM/release + release/Oz9sj9uPbK/release + 9/release + 9/LXE1rW + zc7ey/nT0NbYuLS1xMrCx + nBy6Osy/nS1L/ j0tSyu7 + 8wse80LHGtcS5/second + 1eK1wMzixNG1xLXYt72/second + Gz9s/second + second/a9 + second = "brush: java; "> 1. if target> = 3 * A [n-1], the threshold value is set to H = target-3 * A [0]; 2.if 3 * A [0] <= target <3 * A [n-1], the threshold is set to H = 3 * A [n-1]-3 * A [0]; 3.if target <3 * A [0], the threshold is set to H = 3 * A [n-1]-target.
In this way, you can determine whether the threshold value is the closest to the target value based on the sum of the three values obtained and the target value. Select the scaling direction based on different situations.
Iii. Sample Code
class Solution { public: int threeSumClosest(vector
&num, int target) { int Size = num.size(); sort(num.begin(), num.end()); int MaxSum = 3 * num[Size - 1]; int MinSum = 3 * num[0]; int ThreadHold = 0; if (target <= MinSum) { ThreadHold = MaxSum - target; } if (MaxSum < target) { ThreadHold = target - MinSum; } if ((MinSum < target) && (target <= MaxSum)) { ThreadHold = MaxSum - MinSum; } int Result = 0; for (int Index_outter = 0; Index_outter < (Size - 2); Index_outter++) { int First = num[Index_outter]; int Second = num[Index_outter + 1]; if ((Index_outter != 0) && (First == num[Index_outter - 1])) { continue; } int Start = Index_outter + 1; int End = Size - 1; while (Start < End) { Second = num[Start]; int Third = num[End]; int Sum = First + Second + Third; if (Sum == target) { return Sum; } if (Sum < target) { Start++; if (ThreadHold >= (target - Sum)) { Result = Sum; ThreadHold = target - Sum; } } if (Sum > target) { End--; if (ThreadHold >= (Sum - target)) { Result = Sum; ThreadHold = Sum - target; } } } } return Result; } };
Iv. Summary
The most difficult part of this question lies in the selection of threshold values. In fact, it can be set to the maximum value of an integer. However, I didn't know how to calculate the maximum value of an integer at the beginning. Therefore, the threshold value can only be set based on the relationship between the sum range of the three numbers of sorted arrays and the target. For specific threshold settings, you can draw a number axis for analysis and draw a number axis, everything is clear.