LeetCode_3Sum
1 class Solution { 2 public: 3 vector<vector<int> > threeSum(vector<int> &num) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector<vector<int> > output; 7 if(num.size()<3) return output; 8 9 sort(num.begin(), num.end()); 10 11 for(int i =0; i< num.size() -2 ;){ 12 int startS = i + 1 ; 13 int endS = num.size() - 1 ; 14 while(startS < endS){ 15 16 int sum = num[i] + num[startS] + num[endS]; 17 if(sum == 0) { 18 vector<int> triplet; 19 triplet.push_back(num[i]); 20 triplet.push_back(num[startS]); 21 triplet.push_back(num[endS]); 22 output.push_back(triplet); 23 startS++ ; 24 while(num[startS] == num[startS-1] && startS < endS) startS++; 25 } 26 if(sum < 0) 27 startS ++; 28 else 29 endS --; 30 } 31 i++; 32 while(num[i] == num[i-1] && i< num.size() -2) i ++; 33 } 34 return output; 35 } 36 };
和3Sum closest 类似,注意删除重复的三元组就行
--------------------------------------------------------------------天道酬勤!