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

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

LeetCode 15. 3Sum

2019-11-11 06:20:26
字體:
來源:轉載
供稿:網友

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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 二连浩特市| 岗巴县| 曲沃县| 金门县| 沁水县| 崇州市| 闸北区| 美姑县| 二连浩特市| 无极县| 赤水市| 资兴市| 永靖县| 唐山市| 罗江县| 乐陵市| 三明市| 武清区| 昭通市| 陆丰市| 雷波县| 余江县| 靖宇县| 米脂县| 余干县| 鄂温| 胶州市| 浠水县| 高陵县| 玉门市| 伊宁县| 故城县| 托克托县| 西贡区| 策勒县| 台前县| 青铜峡市| 松原市| 苍南县| 额敏县| 萨嘎县|