3Sum
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)
class Solution { public: // sort and then search from both ends to middle vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > res; int N = num.size(); if(N < 3) return res; sort(num.begin(), num.end()); for(int k = N-1; k >= 2; k--) { if(k != N-1 && num[k] == num[k+1]) { continue; // handle duplicated cases } for(int i = 0, j = k-1; i < j; ) { if(i != 0 && num[i] == num[i-1]) { i++; continue; } if(j != k-1 && num[j] == num[j+1]) { j--; continue; } int sum = num[i] + num[j] + num[k]; if(sum == 0) { vector<int> tmp(3); tmp[0] = num[i]; tmp[1] = num[j]; tmp[2] = num[k]; res.push_back(tmp); i++; j--; } else if(sum < 0) { i++; } else { j--; } } } return res; } };