3Sum

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)

思路:
接着2Sum的思路,只需枚举第一个数,然后判断后两个数和是否是第一个的负数即可。
在判断重复的时候卡了挺久,其实只需保证每次新的判断是和上次不同的子问题就行。

代码:
 1     vector<vector<int> > threeSum(vector<int> &num) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         vector<vector<int> > result;
 5         vector<int> tmp;
 6         result.clear();
 7         tmp.clear();
 8         int len = num.size();
 9         int i, j, k;
10         sort(num.begin(), num.end());
11         for(i = 0; i < len; i++){
12             while(i > 0 && num[i] == num[i-1])
13                 i++;
14             j = i+1;
15             k = len-1;
16             while(j < k){
17                 while(j < k && num[j] == num[j-1] && j > i+1)
18                     j++;
19                 while(j < k && num[k] == num[k+1] && k < len-1)
20                     k--;
21                 if(j >= k)
22                     break;
23                 int t = num[j] + num[k];
24                 if(t < 0 - num[i])
25                     j++;
26                 else if(t > 0 - num[i])
27                     k--;
28                 else{
29                     tmp.push_back(num[i]);
30                     tmp.push_back(num[j]);
31                     tmp.push_back(num[k]);
32                     result.push_back(tmp);
33                     j++;
34                     k--;
35                     tmp.clear();
36                 }
37             }
38         }
39         return result;
40     }

 

posted on 2013-11-07 21:05  waruzhi  阅读(164)  评论(0编辑  收藏  举报

导航