您好,登錄后才能下訂單哦!
這篇文章主要介紹了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++如何解決最近三數之和問題”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“C++如何解決最近三數之和問題”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。