国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

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

LeetCode 15. 3Sum

2019-11-11 07:10:09
字體:
來源:轉載
供稿:網友

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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大安市| 鲁山县| 阿坝| 徐闻县| 涟水县| 缙云县| 大田县| 来宾市| 康保县| 临江市| 福安市| 沂南县| 德阳市| 海阳市| 德化县| 棋牌| 凤庆县| 马山县| 靖西县| 阜南县| 康保县| 富锦市| 尼木县| 海伦市| 慈溪市| 台中市| 固安县| 永新县| 开封市| 巴东县| 正宁县| 泰顺县| 璧山县| 都江堰市| 遵义市| 宁武县| 永春县| 蒙城县| 衢州市| 武安市| 平度市|