您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“C++如何實現最近三數之和”,內容詳細,步驟清晰,細節處理妥當,希望這篇“C++如何實現最近三數之和”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-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; } };
我們還可以稍稍進行一下優化,每次判斷一下,當 nums[i]*3 > target 的時候,就可以直接比較 closest 和 nums[i] + nums[i+1] + nums[i+2] 的值,返回較小的那個,因為數組已經排過序了,后面的數字只會越來越大,就不必再往后比較了,參見代碼如下:
解法二:
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) { if (nums[i] * 3 > target) return min(closest, nums[i] + nums[i + 1] + nums[i + 2]); 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; } };
讀到這里,這篇“C++如何實現最近三數之和”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。