标签:
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:
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
1 class Solution { 2 public: 3 vector<vector<int> > threeSum(vector<int> &num) { 4 5 int n=num.size(); 6 sort(num.begin(),num.end()); 7 8 int i,j,k; 9 int a,b,c; 10 vector<vector<int> > result; 11 12 for(i=0;i<n-2;i++) 13 { 14 j=i+1; 15 k=n-1; 16 17 while(j<k) 18 { 19 a=num[i]; 20 if(i>0&&num[i]==num[i-1]) 21 { 22 break; 23 } 24 b=num[j]; 25 if(j>i+1&&num[j]==num[j-1]) 26 { 27 j++; 28 continue; 29 } 30 31 c=num[k]; 32 if(k<n-1&&num[k]==num[k+1]) 33 { 34 k--; 35 continue; 36 } 37 38 if(a+b+c==0) 39 { 40 vector<int> tmp(3); 41 tmp[0]=a; 42 tmp[1]=b; 43 tmp[2]=c; 44 result.push_back(tmp); 45 j++; 46 k--; 47 } 48 else if(a+b+c<0) 49 { 50 j++; 51 } 52 else if(a+b+c>0) 53 { 54 k--; 55 } 56 } 57 } 58 59 return result; 60 61 } 62 }; 63
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4190319.html