8: 3sum

来源:互联网 发布:图哈切夫斯基 知乎 编辑:程序博客网 时间:2024/06/06 10:07

注:本题的解法思想及参考的代码来自于https://github.com/soulmachine/leetcode#leetcode题解

题目: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:
• Elements in a triplet (a; b; c) must be in non-descending order. (ie, a  b  c)
• 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)

解析方法:先排序,然后左右夹逼,时间是O(n^2)

解题代码如下:

class Solution {public:        vector<vector<int>> threeSum(vector<int>& nums) {                vector<vector<int>> result;                if (nums.size() < 3) return result;                sort(nums.begin(), nums.end());                const int target = 0;                auto last = nums.end();                for (auto i = nums.begin(); i != last - 2; ++i) {                        auto j = i + 1;                        if (i > nums.begin() && *i == *(i - 1)) continue;                        auto k = last - 1;                        while (j < k) {                                if (*i + *j + *k < target) {                                        ++j;//                                      while (*j == *(j - 1) && j < k) ++j;                                }                                else if (*i + *j + *k > target) {                                        --k;//                                      while (*k == *(k + 1) && j < k) --k;                                }                                else {                                        result.push_back(vector<int>{*i, *j, *k});                                        ++j;                                        --k;                                        while (*j == *(j - 1) && j < k)                                                ++j;                                        while (*k == *(k + 1) && j < k)                                                --k;                                }                        }                }                return result;        }};
0 0
原创粉丝点击