码迷,mamicode.com
首页 > 其他好文 > 详细

3Sum

时间:2015-09-10 16:01:05      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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)

 1     vector<vector<int>> threeSum(vector<int>& nums) {
 2      std::sort(nums.begin(), nums.end());  
 3       vector<vector<int> > result;  
 4       int len = nums.size();
 5       int left,right,tmp;
 6       for(int i =1; i< len-1; i++)  
 7       {  
 8         left=i-1;right=i+1;  
 9         //int start = i+1, end =len-1;  
10         while(1)  
11         {  
12           tmp=0-nums[i]-nums[left];
13           if(nums[right] == tmp)  
14           {  
15             vector<int> solution;  
16             solution.push_back(nums[left]);  
17             solution.push_back(nums[i]);  
18             solution.push_back(nums[right]);  
19             result.push_back(solution);  
20             
21             if(left>0)
22             left--;
23             while(left>0&&nums[left]==nums[left-1])
24             left--;
25             if(right<len-1)
26             right++;
27             while(right<len-1&&nums[right]==nums[right+1])
28             right++;
29             //while(start<end && nums[start] == nums[start-1]) start++;  
30             //while(start<end && nums[end] == nums[end+1]) end--;  
31           }  
32            if(left==0&&right==len-1)
33            break;
34            if(nums[right] < tmp)  
35           {  
36             if(right==len-1)
37             break;
38             else
39             right++;
40             
41           }  
42           else  
43           {  
44             if(left==0)
45             break;
46             else
47             left--;  
48           }  
49         }  
50         
51       }  
52       return result;  
53     }  

 

3Sum

标签:

原文地址:http://www.cnblogs.com/hexhxy/p/4797904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!