3Sum -- Leetcode

来源:互联网 发布:ip mac绑定 编辑:程序博客网 时间:2024/06/09 14:29

12.22 2014

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)

class Solution {public:    vector<vector<int> > threeSum(vector<int> &num) {        int len=num.size();        vector<vector<int> > ret;        if(len==0) return ret;                sort(num.begin(), num.end());        for(int i=0;i<len;i++){            if(i > 0 && num[i] == num[i-1])                continue;            int begin=i+1;            int end=len-1;            while(begin<end){                if(num[i]+num[begin]+num[end]>0)                    end--;                else if(num[i]+num[begin]+num[end]<0)                    begin++;                else if(begin!=i+1 && num[begin]==num[begin-1])                    begin++;                else if(end!=len-1 && num[end]==num[end+1])                    end--;                else {                    vector<int> match;                    match.push_back(num[i]);                    match.push_back(num[begin]);                    match.push_back(num[end]);                    ret.push_back(match);                    begin++;                    end--;                }            }        }        return ret;            }};

总结:

1. 这是一个O(n^2)的solution,先取出第i个元素,对其后面的元素进行2sum,由于这里是返回值,那么就不需要使用2sum的hash表来实现。

2. 需要注意不能有duplicate的情况,所以需要多几个判断语句去除duplicate。如第i和i-1的duplicate,和2sum内的duplicate

3. 最后可以使用判断内的变量,省去vector的clear操作。

4. 可以使用vector的iterator提升时间性能。

0 0
原创粉丝点击