【Leetcode】3sum
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)
2 sum 变化而来的题目,首先第一个元素逐个循环,后面的部分采用2sum的思路双指针逼近即可。
1st (12 tries)
class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > re; if(num.size() < 3) return re; sort(num.begin(),num.end()); for(int i = 0;i < num.size() - 2;i++) { vector<int> tmp; tmp.push_back(num[i]); int num1 = num[i]; /*important*/ if(i > 0 && num[i] == num[i - 1]) { continue; } int left = i + 1; int right = num.size() - 1; int preleft = 1024,preright = 1024; while(right > left) { if(num1 + num[right] + num[left] == 0) { /*important*/ if(preleft == num[left] && preright == num[right]) { left ++; right --; } else { tmp.push_back(num[left]); tmp.push_back(num[right]); preleft = num[left]; preright = num[right]; re.push_back(tmp); tmp.pop_back(); tmp.pop_back(); left ++; right --; } } if(num1 + num[right] + num[left] < 0) { left ++; } if(num1 + num[right] + num[left] > 0) { right --; } } } return re; } };
2nd (5 tries)
class Solution { public: vector<vector<int> > ans; vector<int> res; vector<vector<int> > threeSum(vector<int> &num) { sort(num.begin(),num.end()); //scan one with a 2-sum problem int n = num.size(); for(int first = 0;first < n-2;first++) { //remove duplicated if(first > 0 && num[first] == num[first-1]) continue; //2-sum int start = first+1; int end = n - 1; while(start < end) { //remove dup if( start > first+1 && num[start] == num[start-1] && end < n - 1 && num[end] == num[end + 1]) { start++; end--; continue; } if(num[start] + num[end] + num[first] == 0) { res.push_back(num[first]); res.push_back(num[start]); res.push_back(num[end]); ans.push_back(res); res.clear(); start++; end--; } else if(num[start] + num[end] + num[first] > 0) { end--; } else { start++; } } } return ans; } };