标签:
1 class Solution { 2 public: 3 vector<vector<int>> threeSum(vector<int>& nums) { 4 if (nums.size() < 3) 5 return {}; 6 7 sort(nums.begin(),nums.end()); 8 vector<vector<int>> ans; 9 10 for(int i = 0;i < nums.size()-2 ;++i) 11 { 12 int j = i+1; 13 int k = nums.size() - 1; 14 if(i>0 && nums[i] == nums[i-1]) continue; 15 while(j < k) 16 { 17 if(nums[j] + nums[k] == 0 - nums[i]) 18 { 19 vector<int> triplet; 20 triplet.push_back(nums[i]); 21 triplet.push_back(nums[j]); 22 triplet.push_back(nums[k]); 23 ans.push_back(triplet); 24 while(j<k && nums[j] == nums[++j]); 25 } 26 else if(nums[j] + nums[k] < 0 - nums[i]) 27 while(j < k && nums[j] == nums[++j]); 28 else if(nums[j] + nums[k] > 0 - nums[i]) 29 while(j < k && nums[k] == nums[--k]); 30 } 31 } 32 return ans; 33 } 34 35 };
标签:
原文地址:http://www.cnblogs.com/chdxiaoming/p/4784983.html