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: 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]
]
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
var cmp = function(a,b){
return a>b? 1: -1;
};
nums.sort(cmp);
res = [];
var test = [];
var ll=nums.length;
for(var i=0;i<ll;i++){
if(i>0&&nums[i]===nums[i-1]){
continue;
}
var cur = nums[i];
j=i+1;
k = ll-1;
while(j<k){
sum = cur+nums[j]+nums[k];
if(sum === 0){
res.push([nums[i],nums[j],nums[k]]);
while(++j){
if(nums[j]!==nums[j-1]){
break;
}
}
k=ll-1;
}else if(sum>0){
k--;
}else{
j++;
}
}
}
return res;
};