麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發設計 > 正文

LeetCode 15. 3Sum

2019-11-11 05:47:22
字體:
來源:轉載
供稿:網友

15. 3Sum

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:

[

[-1, 0, 1],

[-1, -1, 2]

]

解析

此題的結題思想其實和TwoSum一樣,當我們確定了第一個數字后,第二個和第三個數字就可以用TwoSum一樣的解法求得。 唯一的區別是TwoSum這題只有唯一解,而 3Sum這題可能有多個相同的解,我們需要考慮怎么移除相同的解。

因為返回的是具體的三個數字,而不是數字的下標,所以可以考慮先將輸入的序列進行排序。得到排序后的序列num,長度為n。

將num[i]作為第一個值,檢查序列后面的值中第一個和最后一個值的和 sum = num[i + 1] + num[n-1] 是否等于 target = -num[0]。若sum < target,則說明后兩個值偏小,前一個值贏得后移。否則,若sum > target,則說明后兩個的值偏大,后一個值應當左移。否則,若sum == target,此時找到正確解,暫時保存這3個值。同時應當考慮可能存在的相同的解。因為第一個值已經固定,只需考慮后面2個數不重復出現即可。最后,還要考慮第一個值也可能與后面的值相同。
vector<vector<int> > threeSum(vector<int> &num) {    vector<vector<int> > res;    std::sort(num.begin(), num.end());    for (int i = 0; i < num.size(); i++) {        int target = -num[i];        int front = i + 1;        int back = num.size() - 1;        while (front < back) {            int sum = num[front] + num[back];            // Finding answer which start from number num[i]            if (sum < target)                front++;            else if (sum > target)                back--;            else {                vector<int> triplet(3, 0);                triplet[0] = num[i];                triplet[1] = num[front];                triplet[2] = num[back];                res.push_back(triplet);                // PRocessing duplicates of Number 2                // Rolling the front pointer to the next different number forwards                while (front < back && num[front] == triplet[1]) front++;                // Processing duplicates of Number 3                // Rolling the back pointer to the next different number backwards                while (front < back && num[back] == triplet[2]) rear--;            }        }        // Processing duplicates of Number 1        while (i + 1 < num.size() && num[i + 1] == num[i])             i++;    }    return res;}
github:https://github.com/Subenle/LeetCode-in-Cpp/blob/master/015.md
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 在线播放91| 日韩精品中文字幕一区 | 热99在线视频 | 欧美一级黄视频 | 嫩草影院在线观看网站成人 | 亚洲成人免费影视 | 91看片淫黄大片欧美看国产片 | 黄色毛片18| 香蕉国产9 | 成年人视频免费 | av免费在线观看国产 | 国产成人av一区二区 | 91精品免费在线 | 欧美a久久 | 久草在线视频看看 | 欧美性生交xxxxx久久久缅北 | 久久男 | 国产69精品99久久久久久宅男 | 欧美日韩亚洲国产精品 | 成人免费av在线播放 | 国产午夜精品久久久久久免费视 | 黄色免费在线电影 | 日本在线视频免费 | 国产亚洲精品久久久久久久久 | av成人免费观看 | 色交视频 | 奇米888一区二区三区 | 在线成人免费观看视频 | 美女一级毛片 | 国产羞羞视频在线观看 | 午夜精品一区二区三区免费 | 黄色作爱视频 | 美女一级视频 | 在线观看视频亚洲 | 91 在线免费观看 | 午夜精品成人 | 中文字幕在线观看成人 | 精精国产xxxx视频在线野外 | 一边吃奶一边摸下娇喘 | 国产精品亚洲精品久久 | 鸳鸯谱在线观看高清 |