双指针解决问题 通过两个for循环,固定i下标 left,right两个指针寻找解
/**
* @param {number[]} nums
* @return {number[][]}
*/
不做去重版本
var threeSum = function(nums) {
nums = nums.sort((a, b) => a - b);
console.log(nums)
let result = new Set();
for (let i = 0; i < nums.length - 2; i++) {
if (nums[i] > 0) {
return Array.from(result).map(i => i.split(','));
}
if (i > 0 && nums[i] === nums[i - 1]) {
continue;
}
let cur = nums[i];
let left = i + 1;
let right = nums.length - 1;
while(left < right) {
let sum = cur + nums[left] + nums[right];
if (sum < 0) {
left++
continue;
} else if (sum > 0) {
right--;
continue;
} else {
// res.push([cur, nums[left], nums[right]]);
result.add(`${cur},${nums[left]},${nums[right]}`);
console.log(i, [cur, nums[left], nums[right]])
right--;
left++;
}
}
}
return Array.from(result).map(i => i.split(','));
};