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: 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]
]

分析

ksum问题,有O(n^(k-1))的解法。
本来想尝试O(n^(k-2)log(n))的解法,但是失败了。果然前人都证明了还是有道理的,不过也让我对这个问题的理解更加深刻了。
算法很简单,先排序,再枚举k-2个数,对于剩下的部分用两个索引逼近剩余的值即可。

实现

class Solution {
public:
    vector> threeSum(vector& nums) {
        vector> ans;
        if(nums.size()<3) return ans;
        sort(nums.begin(), nums.end());
        for(int i=0; i0 && nums[i]==nums[i-1])
                continue;
            int begin=i+1, end=nums.size()-1;
            while(begin {nums[i], nums[begin], nums[end]});
                if(nums[i]+nums[begin]+nums[end]<0){
                    do{
                        begin++;
                    }while(begin=0 && nums[end]==nums[end+1]);
                }
            }
        }
        return ans;
    }
};

思考

代码中的两个do-while循环是为了防止重复结果而做的。
提交之后排名不高,所以我看了别人的做了些修改。一是将i++之类的改成++i,据说这样生成的汇编指令会少一点;二是去掉了push_back()函数中的vector,这个好像不需要,会自动转换类型;最后是将这些数的和与要求的结果相等时作为单独的情况,与大于和小于区分开来。然而,在提交之后反而更慢了,让我有点崩溃。题解中循环用的是迭代器,也许这样会快一点,但是我懒得改了,下次注意吧。我修改过的代码虽然慢吧,但是更美观些,也在这边贴一下吧。

class Solution {
public:
    vector> threeSum(vector& nums) {
        vector> ans;
        if(nums.size()<3) return ans;
        sort(nums.begin(), nums.end());
        for(int i=0; i0 && nums[i]==nums[i-1])
                continue;
            int begin=i+1, end=nums.size()-1;
            while(begin=0 && nums[end]==nums[end+1]);
                }
                else if(nums[i]+nums[begin]+nums[end]<0){
                    do ++begin;
                    while(begin=0 && nums[end]==nums[end+1]);
                }
            }
        }
        return ans;
    }
};

你可能感兴趣的:(15. 3Sum)