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)

先对数组进行排序,如果固定一个节点,则问题转化为2sum问题,2sum问题方法如:http://www.cnblogs.com/Scorpio989/p/4392323.html

时间:60ms。代码如下:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector< vector<int> > ret;
        if (nums.size() <= 2)
            return ret;
        sort(nums.begin(),nums.end());
        for (int i = 0; i < nums.size() - 2; ++i){
            if (i >0 && nums[i] == nums[i - 1])
                continue;
            int n = nums.size() - 1, j = i + 1;
            while (j < n){
                if (j > i + 1 && nums[j] == nums[j - 1]){
                    j++;
                    continue;
                }
                if (n > nums.size() - 1 && nums[n] == nums[n + 1]){
                    n--;
                    continue;
                }
                if ((nums[i] + nums[j] + nums[n]) == 0){
                    vector<int> v;
                    v.push_back(nums[i]);
                    v.push_back(nums[j]);
                    v.push_back(nums[n]);
                    ret.push_back(v);
                    j++;
                    n--;
                }
                else if ((nums[i] + nums[j] + nums[n]) > 0)
                    n--;
                else
                    j++;
            }
        }
        return ret;
    }
};

 

posted on 2015-04-19 22:31  NealCaffrey989  阅读(190)  评论(0编辑  收藏  举报