3 Sum

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

C++:
01 vector<vector<int> > threeSum(vector<int> &num) {
02         vector<vector<int> > result;
03         int size=num.size();
04         int *A=new int[size];
05         for(int i=0;i<size;i++)
06             A[i]=num[i];
07         qsort(A,size,sizeof(int),compare);
08         for(int i=0;i<size2;){
09             for(int j=i+1,k=size1;j<; ){
10                 if(A[i]+A[j]+A[k]==0){
11                     vector<int> tmp;
12                     tmp.push_back(A[i]);
13                     tmp.push_back(A[j]);
14                     tmp.push_back(A[k]);
15                     result.push_back(tmp);
16                     do{j++;} while(A[j]==A[j1]);
17                 }
18                 else if(A[i]+A[j]+A[k]<0)
19                     j++;
20                 else
21                     k;
22             }
23             do{i++;} while(A[i]==A[i1]);
24         }
25         return result;
26 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s