LeetCode 3Sum

来源:互联网 发布:机械制图用什么软件 编辑:程序博客网 时间:2024/04/26 17:38

http://www.leetcode.com/onlinejudge

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)

O(n^2) solution:

Reference: http://en.wikipedia.org/wiki/3SUM

Solution:

class Solution {public:    vector<vector<int> > threeSum(vector<int> &num) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        sort(num.begin(),num.end());        vector<vector<int> > result;        vector<int> r(3,0);        for(int i=0;i<num.size();++i){            if(num[i]>0)                break;            if(!result.empty()&&result.back()[0]==num[i])                continue;            int j=i+1,k=num.size()-1;            while(j<k){                if(num[i]+num[j]+num[k]==0){                    if(result.empty()||result.back()[0]!=num[i]||result.back()[1]!=num[j]){                        r[0]=num[i];                        r[1]=num[j];                        r[2]=num[k];                        result.push_back(r);                    }                    ++j;                    --k;                }else if(num[i]+num[j]+num[k]>0){                    --k;                }else{                    ++j;                }            }        }        return result;    }};