LeetCode_3Sum Closest,leetcode_3sum
一.題目3Sum Closest Total Accepted: 32191 Total Submissions: 119262My Submissions
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).Show TagsHave you met this question in a real interview? Yes No
Discuss
二.解題技巧 這道題和另外一道題3Sum類似,主要流程也是一樣的,也是先進行排序,然後按照順序選擇數組A中的第i個元素作為三個數的最小值來尋找三個數的和,不過的地方在於這裡是尋找最靠近給定值,尋找最靠近的值就無所有重複的事情了,所以可以不考慮夾逼的過程中的越過相同元素的過程,雖然越過相同的元素速度會快一些,但是代碼長度也會加長。 這道題難的地方可能在於剛開始這種差的閾值的過程,如果把閾值設定得太小了,會出現錯誤,因此,應該儘可能地將閾值設定得大一點。由於數組是已經排序的,因此,數組中三個數的和的範圍在[3*A[0], 3*A[n-1]],因此,閾值可以根據下面三種情況進行設定:
1.if target >= 3*A[n-1],閾值設定為H = target - 3 * A[0];2.if 3*A[0] <= target<3*A[n-1],閾值設定為H = 3 * A[n-1] - 3*A[0];3.if target < 3 * A[0],閾值設定為H = 3 * A[n-1] - target。
這樣就可以根據閾值與目前得到的三個數的和與target的差來判斷是否是最接近target的情況了,根據不同的情況,選擇縮放的方向。
三.實現代碼
class Solution{public: int threeSumClosest(vector<int> &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; }};
四.體會 這道題最難的地方在於閾值的選擇上面,其實可以設定為整數的最大值的,但是,我一開始並不知道如何計算整數的最大值,因此,只能根據排好序的數組的三個數的和的範圍與target的關係來設定閾值了,具體的閾值設定情況可以畫個數軸出來分析,畫出數軸之後,一切就明顯了。
著作權,歡迎轉載,轉載請註明出處,謝謝