SOURCE

/**
 * 这个三数的target默认是0
 * 双指针
 */
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 = []

    // 这里的长度减不减1,其实都一样
    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 命令行工具 X clear

                    
>
console