Fork me on GitHub

[leetcode-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]
]

思路:

1.首先排序。

2.固定一个元素,然后在此元素后求2sum。

    void getTwoSum(vector<vector<int>>& result, vector<int>& nums, int begin, int end, int target)
    {
        int i = begin, j = end;
        while (i < j)
        {
            if (nums[i] + nums[j] + target == 0)
            {    
                vector<int>temp;
                temp.push_back(target);
                temp.push_back(nums[i]);
                temp.push_back(nums[j]);
                result.push_back(temp);
                 
                while (i < j && nums[i] == nums[i + 1])
                    ++i;
                while (i < j && nums[j] == nums[j - 1])
                    --j;
                ++i;
                --j;
            }
            else if (nums[i] + nums[j] + target < 0)
                ++i;
            else
                --j;
        }
    }
    vector<vector<int>> threeSum(vector<int>& nums)
    {
        vector<vector<int>>result;
        vector<int> temp;
        if (nums.size() < 3)
            return result;
        sort(nums.begin(),nums.end());
        for (int i = 0; i < nums.size()-2;i++)
        {
            if (i>0 && nums[i] == nums[i-1])
                continue;
            getTwoSum(result,nums,i+1,nums.size()-1,nums[i]);
        }    
        return result;
    }

参考:

http://blog.csdn.net/lisonglisonglisong/article/details/45848209

posted @ 2017-03-10 10:24  hellowOOOrld  阅读(171)  评论(0编辑  收藏  举报