标签:
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:
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 }
标签:
原文地址:http://www.cnblogs.com/hexhxy/p/4797904.html