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)

这道题能够用求两个数的和同样的解法来求解。须要注意的是对反复元素的处理。假设不加上这个减枝处理,在leetcode中会显示超时。


首先对数组进行排序,时间复杂度是O(Nlog(N))。
然后定义三个指针,第一个指针从头遍历到尾,第二个指针和第三个指针和求两个数的和时的那两个指针一样从两端開始遍历,左端由第一个指针来确定。

这样时间复杂度是O(N^2)。总的时间复杂度是O(N^2)。一定要加上对反复元素的减枝处理。

runtime:68ms

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int length=nums.size();
        vector<vector<int>> result;
        if(length<3)
            return result;

        sort(nums.begin(),nums.end());
        auto iter1=nums.begin();
        for(;iter1!=nums.end()-2;iter1++)
        {
            auto iter2=iter1+1;
            auto iter3=nums.end()-1;
            while(iter2<iter3)
            {
                if(*iter1+*iter2+*iter3==0)
                {
                    vector<int> tmp;
                    tmp.push_back(*iter1);
                    tmp.push_back(*iter2);
                    tmp.push_back(*iter3);
                    result.push_back(tmp);
                    while(*iter2==*(iter2+1)&&(iter2+1)<iter3) iter2++;
                    while(*iter3==*(iter3-1)&&iter2<(iter3-1)) iter3--;
                    iter2++;
                }
                else if(*iter1+*iter2+*iter3<0)
                {
                    while(*iter2==*(iter2+1)&&(iter2+1)<iter3) iter2++;
                    iter2++;
                }
                else
                {
                    while(*iter3==*(iter3-1)&&iter2<(iter3-1)) iter3--;
                    iter3--;
                }
            }
            while(*iter1==*(iter1+1)&&(iter1+1)<nums.end()-2) iter1++;
        }
        return result;

    }
};