日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode No.15-16 三数之和相关问题

發布時間:2024/7/23 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 三数之和相关问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。