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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
去重比较麻烦,在外层循环同样的元素只用一次,在内层循环,每次匹配后,跳过所有与当前匹配相同的元素。
1 class Solution { 2 public: 3 vector<vector<int> > threeSum(vector<int> &num) { 4 vector<vector<int> > res; 5 if (num.size() < 3) { 6 return res; 7 } 8 sort(num.begin(), num.end()); 9 int low, high; 10 for (int i = 0; i < num.size() - 2; ++i) { 11 if (i > 0 && num[i] == num[i-1]) continue; 12 low = i + 1; 13 high = num.size() - 1; 14 while (low < high) { 15 int sum = num[i] + num[low] + num[high]; 16 if (sum > 0) { 17 --high; 18 } else if (sum < 0) { 19 ++low; 20 } else { 21 vector<int> tmp; 22 tmp.push_back(num[i]); 23 tmp.push_back(num[low]); 24 tmp.push_back(num[high]); 25 res.push_back(tmp); 26 while (low < num.size() - 1 && num[low] == num[low+1]) 27 ++low; 28 while (high > 0 && num[high] == num[high-1]) 29 --high; 30 ++low; 31 --high; 32 } 33 } 34 } 35 return res; 36 } 37 };