LeetCode 3Sum

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)

 

枚举第一个数,然后在其后的数组设置两个指针。O(n^2)

 1 class Solution {
 2 private:
 3     vector<vector<int> > ret;
 4 public:
 5     vector<vector<int> > threeSum(vector<int> &num) {
 6         // Start typing your C/C++ solution below
 7         // DO NOT write int main() function
 8         ret.clear();
 9         sort(num.begin(), num.end());
10         
11         for(int i = 0; i < num.size(); i++)
12         {
13             if (i > 0 && num[i] == num[i-1])
14                 continue;
15                 
16             int j = i + 1;
17             int k = num.size() - 1;
18             
19             while(j < k)
20             {
21                 if (j > i + 1 && num[j] == num[j-1])
22                 {
23                     j++;
24                     continue;
25                 }
26                 
27                 if (k < num.size() - 1 && num[k] == num[k+1])
28                 {
29                     k--;
30                     continue;
31                 }
32                 
33                 int sum = num[i] + num[j] + num[k];
34                 
35                 if (sum == 0)
36                 {
37                     vector<int> a;
38                     a.push_back(num[i]);
39                     a.push_back(num[j]);
40                     a.push_back(num[k]);
41                     ret.push_back(a);
42                     j++;
43                 }
44                 else if (sum < 0)
45                 {
46                     j++;
47                 }
48                 else
49                 {
50                     k--;
51                 }
52             }
53         }
54         
55         return ret;
56     }
57 };
posted @ 2012-10-27 19:12  chkkch  阅读(1108)  评论(0编辑  收藏  举报