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:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, abc)
  • The solution set must not contain duplicate triplets.

这题意思很明显。顺序的找出所有三个元素相加为零的元素。即两个要求:

1:a+b+c=0;

2:三个数输出a<b<c,而且a1<a2<...<an.

最开始我想到的是利用一个和s等长的表挨个统计每个元素的个数,重复的首个元素对应位置记录其个数,其他位置的此元素对应位置记录为-1, 分别按有三个相同元素,有两个相同元素,三个互异的元素,来寻找,时间复杂度0(n^3),显然oj通不过。

比较好的解法是,先对元素进行排序,然后在进行查找,此时就可以利用元素相邻之间的大小关系,省去一些重复的查找,具体实现如下:

vector<vector<int>> threeSum(vector<int> &num)
{
    int nSize = num.size();
    vector<vector<int>> res;

    if(nSize < 3)
    {
        return res;
    }
    
    for(int i = 0; i!= nSize; ++i)
    {
        if(i!=0 && num[i-1]==num[i])
        {
            continue;
        }

        insertsort2(num);

        int p = i+1; 
        int q = nSize - 1;
        while(p < q)
        {
            int sum = num[i] + num[p] + num[q];
            if(sum == 0)
            {
                vector<int> vTemp;
                vTemp.push_back(num[i]);
                vTemp.push_back(num[p]);
                vTemp.push_back(num[q]);
                res.push_back(vTemp);
                while(++p < q && num[p] == num[p-1]);
                while(--q > p && num[q] == num[q+1]);
            }
            else if(sum < 0)
            {
                ++p;
            }
            else if(sum > 0)
            {
                --q;
            }
        }

    }
    return res;
}
void insertsort2(vector<int> &num)
{
    int nSize = num.size();
    int j = 0;

    for(int i = 1; i< nSize; ++i)
    {
        int temp = num[i];
        for( j = i; j>0 && temp < num[j-1] ; --j)
        {
            num[j] = num[j-1]; 
        }
        num[j] = temp;
    }
}

排序算法果然是普遍的应用,必须熟练的掌握,就像记英语单词一样!

原文地址:https://www.cnblogs.com/bestwangjie/p/4458275.html