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:首先想到暴力破解,O(n^3)的时间复杂度,必然超时Time Limit Exceeded。
class Solution { public: vector< vector<int> > threeSum(vector<int>& nums) { int n = nums.size(); vector< vector<int> > res; if (n < 3) return res; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { if (nums[i] + nums[j] + nums[k] == 0) { vector<int> vi = adjust(nums[i], nums[j], nums[k]); vector< vector<int> >::iterator iter = find(res.begin(), res.end(), vi); if (iter == res.end()) res.push_back(vi); } } } } return res; } private: vector<int> adjust(int& a, int& b, int&c) { if (a > b) swap(a, b); if (a > c) { swap(a, c); swap(b, c); } else { if (b > c) swap(b, c); } vector<int> vi; vi.push_back(a); vi.push_back(b); vi.push_back(c); return vi; } };
解法2:假设3sum问题的目标是target。每次从数组中选出一个数k,从剩下的数中求目标等于target-k的2sum问题。这里需要注意的是有个小的trick:当我们从数组中选出第i数时,我们只需要求数值中从第i+1个到最后一个范围内字数组的2sum问题。假设数组为A[],总共有n个元素A1,A2....An。很显然,当选出A1时,我们在子数组[A2~An]中求目标位target-A1的2sum问题,我们要证明的是当选出A2时,我们只需要在子数组[A3~An]中计算目标位target-A2的2sum问题,而不是在子数组[A1,A3~An]中,证明如下:
假设在子数组[A1,A3~An]目标位target-A2的2sum问题中,存在A1 + m = target-A2(m为A3~An中的某个数),即A2 + m = target-A1,这刚好是“对于子数组[A2~An],目标为target-A1的2sum问题”的一个解。即我们相当于对满足3sum的三个数A1+A2+m = target重复计算了。因此为了避免重复计算,在子数组[A1,A3~An]中,可以把A1去掉,再来计算目标是target-A2的2sum问题。
class Solution { public: vector< vector<int> > threeSum(vector<int>& nums) { int n = nums.size(); vector< vector<int> > res; if (n < 3) return res; sort(nums.begin(), nums.end()); for(int i = 0; i < n; i++) { if(i == 0 || (i > 0 && nums[i] != nums[i - 1])) { int left = i + 1, right = n - 1; int sum = 0 - nums[i]; while(left < right) { if(nums[left] + nums[right] == sum) { vector<int> vi; vi.push_back(nums[i]); vi.push_back(nums[left]); vi.push_back(nums[right]); res.push_back(vi); while(left < right && nums[left] == nums[left + 1]) left++; while(left < right && nums[right] == nums[right - 1]) right--; left++; right--; } else if(nums[left] + nums[right] < sum) left++; else right--; } } } return res; } };
参考:http://www.cnblogs.com/tenosdoit/p/3649607.html