标签:
For this problem, do not forget to skip the duplicates for i. Usually I will do duplication removal for j and k.
Tag it.
1 class Solution { 2 public: 3 vector<vector<int> > threeSum(vector<int> &num) { 4 vector<vector<int> > result; 5 int len = num.size(), i = 0, j = 0, k = 0; 6 if (len < 2) return result; 7 sort(num.begin(), num.end()); 8 for (int i = 0; i < len-2; i++) { 9 if (i > 0 && num[i] == num[i-1]) continue; 10 j = i+1, k = len-1; 11 while (j < k) { 12 int sum = num[i] + num[j] + num[k]; 13 if (sum > 0) k--; 14 else if (sum < 0) j++; 15 else { 16 vector<int> tmp; 17 tmp.push_back(num[i]); 18 tmp.push_back(num[j]); 19 tmp.push_back(num[k]); 20 result.push_back(tmp); 21 do{j++;} while (j < k && num[j] == num[j-1]); 22 do{k--;} while (j < k && num[k] == num[k+1]); 23 } 24 } 25 } 26 return result; 27 } 28 };
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/4346149.html