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).
這道題讓我們求最接近給定值的三數之和,是在之前那道 3Sum 三數之和的基礎上又增加了些許難度,那麼這道題讓我們返回這個最接近於給定值的值,即我們要保證當前三數和跟給定值之間的差的絕對值最小,所以我們需要定義一個變數diff用來記錄差的絕對值,然後我們還是要先將陣列排個序,然後開始遍歷陣列,思路跟那道三數之和很相似,都是先確定一個數,然後用兩個指標left和right來滑動尋找另外兩個數,每確定兩個數,我們求出此三數之和,然後算和給定值的差的絕對值存在newDiff中,然後和diff比較並更新diff和結果closest即可,程式碼如下:
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int closest = nums[0] + nums[1] + nums[2]; int diff = abs(closest - target); sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size() - 2; ++i) { int left = i + 1, right = nums.size() - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; int newDiff = abs(sum - target); if (diff > newDiff) { diff = newDiff; closest = sum; } if (sum < target) ++left; else --right; } } return closest; } };