3SumJan 18 '128685 / 33750
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)
class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { sort(num.begin(), num.end()); vector<vector<int> > res; int len = num.size(); for (int i = 0; i < len - 2; i++) { if (i > 0 && num[i] == num[i-1]) continue; int a = i+1, b = len -1; int t = -num[i]; while (a < b) { if (num[a] + num[b] == t) { int tmp[3] = {-t, num[a], num[b]}; vector<int> tmp2(tmp, tmp+3); res.push_back(std::move(tmp2)); while (a < b && num[a] == num[a+1]) a++; a++; while (a < b && num[b] == num[b-1]) b--; b--; } else if (num[a] + num[b] > t) { b--; } else a++; } } return res; } };