code第一部分数组:第七题 给定数组三个元素求和为0

code第一部分数组:第七题 给定数组三个元素求和为0

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.

分析
根据题目条件,总共可以有三种方法来解答,下面一一分析;
解决放大1:暴力法
就是暴力解答,直接三次循环,当然,因为存在重复的,最后记得要去重;时间复杂度为O(n的三次方)
在这里就不写代码了;
解决方法2
先排序,然后二分查找,就是先指定两个数,第三个数同二分查找寻找;复杂度 O(n²log n)。
源代码如下
解决方法3
还是先排序,但是左右夹逼查找,时间复杂度为O(N²)

//解决方法2
vector<vector<int> threesum(vector<int > &num)
{
    vector<vector<int>> result;
    if (num.size()<3)
    {
        return result;
    }
    sort(num.begin(),num.end());

    const target=0;

    for (auto a = num.begin; a < prev(last,2); a=next(a))
    {

        for (auto b = next(a); b < prev(last);b = upper_bound(b, prev(last), *b))
        {
            const int c = target - *a - *b;
            //二分查找
            if (binary_search(next(b), last, c))
                result.push_back(vector<int> { *a, *b, c });
        }

    }

    return result;
}


//解决方法3
vector<vector<int> > three_sum(vector<int> &num)
{
    vector<vector<int> > ret;

    if (num.size() == 0)
        return ret;

    sort(num.begin(), num.end());

    for (vector<int>::const_iterator it = num.begin();it != num.end();++it)
    {
        // Dedup
        if (it != num.begin() && *it == *(it - 1))
        {
            continue;
        }

        // Dedup, front = it + 1
        vector<int>::const_iterator front = it + 1;
        vector<int>::const_iterator back = num.end() - 1;

        while (front < back)
        {
            const int sum = *it + *front + *back;

            if (sum > 0)
            {
                --back;
            }
            else if (sum < 0)
            {
                ++front;
            }
            // Dedup
            else if (front != it + 1 && *front == *(front - 1))
            {
                ++front;
            }
            // Dedup
            else if (back != num.end() - 1 && *back == *(back + 1))
            {
                --back;
            }
            else
            {
                vector<int> result;
                result.push_back(*it);
                result.push_back(*front);
                result.push_back(*back);

                ret.push_back(result);

                ++front;
                --back;
            }
        }
    }

    return ret;
}
原文地址:https://www.cnblogs.com/tao-alex/p/6443015.html