类似于2sum,先排序,然后从左开始遍历,计算a[i]后面的等于-a[i]的两个元素,
注意去除重复元素
1 class Solution { 2 public: 3 vector<vector<int> > threeSum(vector<int> &num) { 4 vector<vector<int> > res; 5 sort(num.begin(),num.end()); 6 int n = num.size(); 7 for(int i = 0 ; i < n-2 ; ++i){ 8 if(i > 0 && (num[i] == num[i-1])){ 9 continue; 10 } 11 int target = -num[i]; 12 int left = i+1; 13 int right = n-1; 14 while(left < right){ 15 if(target == num[left] + num[right]){ 16 vector<int> triplet; 17 triplet.push_back(num[i]); 18 triplet.push_back(num[left]); 19 triplet.push_back(num[right]); 20 res.push_back(triplet); 21 left++; 22 while((left < right) && (num[left] == num[left-1])){ 23 left++; 24 } 25 right--; 26 while((right > left) && (num[right] == num[right+1])){ 27 right--; 28 } 29 } 30 else if(target > num[left] + num[right]){ 31 left++; 32 while((left < right) && (num[left] == num[left-1])){ 33 left++; 34 } 35 } 36 else{ 37 right--; 38 while((right > left) && (num[right] == num[right+1])){ 39 right--; 40 } 41 } 42 } 43 } 44 return res; 45 } 46 };