日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

算法--三数之和

發布時間:2025/6/15 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 算法--三数之和 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

??強烈推薦人工智能學習網站??? ? ??

給你一個包含 n 個整數的數組?nums,判斷?nums?中是否存在三個元素 a,b,c ,使得?a + b + c = 0 ?請你找出所有滿足條件且不重復的三元組。

注意:答案中不可以包含重復的三元組。

示例:

給定數組 nums = [-1, 0, 1, 2, -1, -4],

滿足要求的三元組集合為:
[
? [-1, 0, 1],
? [-1, -1, 2]
]

解題思路:排序+雙指針

class Solution { public:vector<vector<int>> threeSum(vector<int>& nums) {int n = nums.size();sort(nums.begin(), nums.end());vector<vector<int>> ans;// 枚舉 afor (int first = 0; first < n; ++first) {// 需要和上一次枚舉的數不相同,數組里面有相同的元素if (first > 0 && nums[first] == nums[first - 1]) {continue;}// c 對應的指針初始指向數組的最右端int third = n - 1;int target = -nums[first];// 枚舉 bfor (int second = first + 1; second < n; ++second) {// 需要和上一次枚舉的數不相同,數組里面有相同的元素if (second > first + 1 && nums[second] == nums[second - 1]) {continue;}// 需要保證 b 的指針在 c 的指針的左側while (second < third && nums[second] + nums[third] > target) {--third;}// 如果指針重合,隨著 b 后續的增加// 就不會有滿足 a+b+c=0 并且 b<c 的 c 了,可以退出循環if (second == third) {break;}if (nums[second] + nums[third] == target) {ans.push_back({nums[first], nums[second], nums[third]});}}}return ans;} };

target 是需要固定的數,如果target為-3,那只需要second+third=3就符合結果,second是左邊的指針,third是右邊的指針。因為整個數組是升序的,如果second+third>3,這說明合大了,所有third指針需要移動;如果second+third<3,則second指針需要移動。

?

?

參考地址:https://leetcode-cn.com/problems/3sum/solution/san-shu-zhi-he-by-leetcode-solution/

?

總結

以上是生活随笔為你收集整理的算法--三数之和的全部內容,希望文章能夠幫你解決所遇到的問題。

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