leetcode-15 3Sum

来源:互联网 发布:2017淘宝卖家参加双12 编辑:程序博客网 时间:2024/06/05 04:50
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.
For example, given array S = {-1 0 1 2 -1 -4}.
A solution set is:(-1, 0, 1) (-1, -1, 2)

先排序,然后外层一次循环,里面左右夹逼,复杂度O(n2)。
这个方法可以推广到k-sum,先排序,然后做k-2 次循环,在最内层循环左右夹逼,时间复
杂度是O(max(n log n, n^(k-1))。

//////////////////////////////////////////////////////////////////////////
// start: find all three numbers which gives the sum of zero
// 注意解是否重复
vector<vector<int>> threeSum(vector<int>& nums)
{
    vector<vector<int>> result;
    int len = nums.size();
    if(len <= 2)
        return result;

    sort(nums.begin(), nums.end());
    int target = 0; 
    for(int i = 0; i < len-2; i++)  // 三个index,两个从头开始,一个从末尾开始
    {
        int j = i + 1;
        int k = len - 1;
        while(j < k)
        {
            if(nums[i]+nums[j]+nums[k] < target)
                j++;
            else if(nums[i]+nums[j]+nums[k] > target)
                k--;
            else
            {
                result.push_back({i, j, k});  
                j++;
                k--;
                while(j < k && nums[j] == nums[j-1])  // 当相邻数相同时这样会出现重复(nums[j]==nums[j-1])
                    j++;
                while(j < k && nums[k] == nums[k+1])  // (nums[k]==nums[k+1])
                    k--;
            }
        }
        while(i < len-2 && nums[i] == nums[i+1])  // (nums[i]==nums[i+1]) 当下一个i和本次的i相同时,本次已经计算过
            i++;
    }

    // sort and unique will cost a lot of time 最后做删除时会超时  
    // sort(ret.begin(), ret.end()); 
    // ret.erase(unique(ret.begin(), ret.end()), ret.end());
    return result;
}
// end
//////////////////////////////////////////////////////////////////////////
0 0