leetcode No.15-16 三数之和相关问题
leetcode 15. 三數之和
題目
鏈接:https://leetcode-cn.com/problems/3sum
給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重復的三元組。
注意:答案中不可以包含重復的三元組。
示例:
給定數組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[
[-1, 0, 1],
[-1, -1, 2]
]
C++代碼
首先最直接的解法顯然是暴力循環,將所有可能的情況都遍歷一遍。
這樣所需要嵌套三個for循環,因此時間復雜度O(N3),顯然無法接受。
如何優化呢?我沒有思路,考慮先將問題簡化。
可以對給定數組進行排序,變為有序數組,而排序的時間復雜度時O(NlogN),在暴力法面前不值一提,因此這個思路可行。
當數組有序時,我們就有辦法處理了。問題變為了:
固定三元組中的最小數,找到 b + c = -a
既然是有序數組,我們就可以用雙指針法,不斷縮小可取值的范圍,直到左指針l<右指針r的條件不滿足
另外,需要思考下如何處理滿足條件的三元組不唯一的情況,以及如何去重。
class Solution { public:vector<vector<int>> threeSum(vector<int>& nums) {int target;vector<vector<int>> ans;sort(nums.begin(), nums.end());for (int i = 0; i < nums.size(); i++) {if (i > 0 && nums[i] == nums[i - 1]) continue;if ((target = nums[i]) > 0) break;int l = i + 1, r = nums.size() - 1;while (l < r) {if (nums[l] + nums[r] + target < 0) ++l;else if (nums[l] + nums[r] + target > 0) --r;else {ans.push_back({target, nums[l], nums[r]});++l, --r;while (l < r && nums[l] == nums[l - 1]) ++l;while (l < r && nums[r] == nums[r + 1]) --r;}}}return ans; } };leetcode 16. 最接近的三數之和
題目
鏈接:https://leetcode-cn.com/problems/3sum-closest/
給定一個包括 n 個整數的數組 nums 和 一個目標值 target。找出 nums 中的三個整數,使得它們的和與 target 最接近。返回這三個數的和。假定每組輸入只存在唯一答案。
例如,給定數組 nums = [-1,2,1,-4], 和 target = 1.
與 target 最接近的三個數的和為 2. (-1 + 2 + 1 = 2).
C++代碼
依舊延續leetcode NO.15 三數之和的方案,沒有思路,先將問題簡化,對數組nums進行排序,轉為有序數組。
此時,我們依然可以使用雙指針法來求解本問題。
注意思考:如何證明雙指針法在逐漸收縮的過程中不會錯過最優解?
class Solution { public:int threeSumClosest(vector<int>& nums, int target) {int total_best_sum = -1;int total_min_dict = INT_MAX;if(nums.size() < 3)return total_best_sum;// 首先對數組進行排序sort(nums.begin(), nums.end());for(int i = 0; i < nums.size() - 2; i++){int a = nums[i];int residual = target - a;int l = i + 1;int r = nums.size() - 1;int min_dict = INT_MAX;int best_sum = -1;while(l < r){int cur_threeSum = a + nums[l] + nums[r];int cur_dict = abs(target - cur_threeSum);if(cur_dict == 0)return target;if(cur_dict < min_dict){min_dict = cur_dict;best_sum = cur_threeSum;}if(target - cur_threeSum > 0)l++;elser--;}// 結束了a = nums[i]時最優三元組的尋找,判斷是否為總體最優if(min_dict < total_min_dict){total_min_dict = min_dict;total_best_sum = best_sum;}}return total_best_sum;} };執行用時: 4 ms, 在所有 C++ 提交中擊敗了 99.46% 的用戶
內存消耗: 12.2 MB, 在所有 C++ 提交中擊敗了 5.14% 的用戶
總結
以上是生活随笔為你收集整理的leetcode No.15-16 三数之和相关问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天池CV学习赛:街景字符识别-思路与上分
- 下一篇: 外设驱动库开发笔记29:DS17887实