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)

思路:对数组排序,然后从左到右遍历数组。对于数组中的每个元素S[i],要在它后面的全部元素中找两个元素令0=S[i]+S[j]+S[k],即-S[i]=S[j]+S[k],则将3sum问题转化为了2sum问题。能够採用hash的方法求解,也能够採用双指针法求解,我採用的是双指针法。


代码:

vector<vector<int> > Solution::threeSum(vector<int> &num)
{
    int i,j,k;
    vector<vector<int> > result;
    int length = num.size();
    if(length <= 2)
        return result;
    sort(num.begin(),num.end());
    for(i = 0;i < length - 2;)
    {
        int two_sum = 0 - num[i];
        for(j = i+1,k = length-1;j < k;)
        {
            if((num[j] + num[k]) < two_sum)
                j++;
            else if(two_sum == (num[j] + num[k]))
            {
                vector<int> temp(3);
                temp[0] = num[i];
                temp[1] = num[j];
                temp[2] = num[k];
                result.push_back(temp);
                do
                    j++;
                while(j < k && num[j] == num[j-1]);
                do
                    k--;
                while(j < k && num[k] == num[k+1]);
            }
            else if(two_sum < (num[j] + num[k]))
                k--;
        }
        do
            i++;
        while(i < num.size() - 2 && num[i-1] == num[i]);
    }
    sort(result.begin(),result.end());
    return result;
}


你可能感兴趣的:(LeetCode)