題目詳情
給定一個包括 n 個整數的數組 nums 和 一個目標值 target。找出 nums 中的三個整數,使得它們的和與 target 最接近。返回這三個數的和。假定每組輸入只存在唯一答案。
示例:
輸入:nums = [-1,2,1,-4], target = 1
輸出:2
解釋:與 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
提示:
- 3 <= nums.length <= 10^3
- -10^3 <= nums[i] <= 10^3
- -10^4 <= target <= 10^4
——題目難度:中等
這道題和15. 三數之和的解法其實差不了很多,只是在second和third的移動上有些差別。但是解題時保證不重複的核心還是先得對nums進行排序。
設delta = nums[first] + nums[second] + nums[third] - target,當delta = 0,當然就是和target最接近 直接返回即可;
當delta > 0,說明nums[first] + nums[second] + nums[third] 大於 target,那麼就需要縮小 三數之和 ,因爲second只能往右移動,這樣會導致 三數之和 越來越大,所以只能讓third往左移動;
當delta < 0,說明nums[first] + nums[second] + nums[third] 小於 target,那麼就需要增大 三數之和 ,因爲third只能往左移動,這樣會導致 三數之和 越來越小,所以只能讓second往右移動。
-代碼如下
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size();
int ansSum = nums[0] + nums[1] + nums[2];
for (int first = 0; first < n - 2; first++)
{
if (first > 0 && nums[first] == nums[first-1])
continue;
int second = first + 1;
int third = n - 1;
while (second < third) {
int tmpSum = nums[first] + nums[second] + nums[third];
if (abs(ansSum - target) > abs(tmpSum - target)) {
ansSum = tmpSum;
}
//delta = nums[first] + nums[second] + nums[third] - target
int delta = tmpSum - target;
if (delta == 0) {
return ansSum;
}
else if (delta > 0) { //nums[first] + nums[second] + nums[third] > target
third--;
}
else { //nums[first] + nums[second] + nums[third] < target
second++;
}
}
}
return ansSum;
}
};
結果(有點慢呀...)