function threeNum(nums) {
function twoNum(target, low, up) {
const sum = nums[low] + nums[up]
if (sum === target) {
return [low, up]
} else {
if (sum < target) {
low++
} else {
up--
}
}
return [null, null]
}
nums.sort((a, b) => a - b)
const result = []
for (let i = 0; i < nums.length - 1; i++) {
if (nums[i] === nums[i - 1]) {
continue
}
let [low, up] = [i + 1, nums.length - 1]
while (low < up) {
[low, up] = twoNum(-nums[i], low, up)
if (low === null || up === null) {
break
}
result.push([nums[i], nums[low], nums[up]])
low++
up--
while (nums[low] === nums[low - 1]) {
low++
}
while (nums[up] === nums[up + 1]) {
up--
}
}
}
return result
}
console.log(threeNum([-1, 0, 1, 2, -1, -4]))
console