3Sum

Question:

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)

Solution:
 1 class Solution {
 2 public:
 3     vector<vector<int>> threeSum(vector<int>& nums) {
 4     vector< vector<int> > result;
 5     if(nums.size()<3)
 6         return result;
 7     sort(nums.begin(),nums.end());
 8     const int target=0;
 9     auto last=nums.end();
10     for(auto i=nums.begin();i<last-2;i++)
11     {
12         auto j=i+1;
13         if(i>nums.begin() && *i==*(i-1)) continue;
14         auto k=last-1;
15         while(j<k)
16         {
17             if(*i+*j+*k<target)
18                 {j++;while(*j==*(j-1) && j<k) ++j;}
19             else if(*i+*j+*k>target)
20                 {k--;while(*k==*(k+1) && j<k) --k;}
21             else
22             {
23                 vector<int> x;
24                 x.push_back(*i);
25                 x.push_back(*j);
26                 x.push_back(*k);
27                 result.push_back(x);
28                 ++j;
29                 --k;
30                 while(*j==*(j-1) && *k==*(k+1) && j<k) ++j;
31             }
32         }
33     }
34     return result;
35     }
36 };


posted on 2015-07-08 21:57  Riden  阅读(168)  评论(0编辑  收藏  举报

导航