leetcode : 3sum

Given an array S of n integers, are there elements abc 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)

 

思路还是先排序然后慢慢找,有意思的地方在于去重。
在得到一个和为0的i left 与 right 之后,再将附近的重复元素去掉就可以避免漏掉类似-2,1,1这样组合,并去掉重复组合
AC代码:
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int>> ret;
        if(num.size() < 3)
            return ret;
        sort(num.begin(), num.end());
        for(int i = 0; i < num.size() - 2; ++i){
            int left = i + 1;
            int right = num.size() - 1;
            while(left < right){
                if(num[left] + num[right] + num[i] > 0){
                    --right;
                }else if(num[left] + num[right] + num[i] < 0){
                    ++left;
                }else{
                    ret.push_back(vector<int>{num[i], num[left], num[right]});
                    while(right > left && num[right] == num[(right--) - 1])         //num[right]为最后一个重复元素,并且对right自减,left同理
                        ;
                    while(left < right && num[left] == num[(left++) +1])
                        ;
                }
            }
            while(i < num.size() - 1 && num[i + 1] == num[i])
                ++i;
        }
        return ret;
    }
};

 

posted on 2014-12-06 23:08  远近闻名的学渣  阅读(185)  评论(1)    收藏  举报

导航