双指针妙解三数之和

三数之和算是名气很大的算法题,我今天刚好刷到,用JavaScript实现了一下。
题目如下所示:

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

 

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: 
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
 

Constraints:

3 <= nums.length <= 3000
-105 <= nums[i] <= 105

相比之前一道两数之和,三数之和的难度增加了一些,变量变成了3个,并且不止一个解。如果还是用暴力破解的算法就需要3个嵌套循环,这样算法的时间复杂度就是n^3,是非常差的算法。
这里可以思考把第一个数当成一个固定的数,通过遍历的方式逐一尝试,这样就可以变回我们熟悉的两数之和的套路了。通过两个指针,不断推移,当3个数加起来等0的时候,把当前三个数加到结果的数组里面,然后继续寻找下一个解。其中要注意处理重复的值,当有重复项出现,就移动指针到下一个,减少重复对比,提高效率。

具体实现如下所示:


/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    // Sort the array named nums
    const sortedNums = nums.sort((a, b) => a - b);

    const result = [];

    for (let i = 0; i < sortedNums.length - 2; i++) {
        // Skip the duplicated item
        if (i > 0 && sortedNums[i] === sortedNums[i - 1]) continue;

        let left = i + 1;
        let right = sortedNums.length  - 1;

        while(left < right) {
            let total = sortedNums[i] + sortedNums[left] + sortedNums[right];

            if (total === 0) {
                result.push([sortedNums[i], sortedNums[left], sortedNums[right]]);
                // Handle the duplicated item
                while(left < right && sortedNums[left] === sortedNums[left + 1]) {
                    left += 1;
                }

                while(left < right && sortedNums[right] === sortedNums[right - 1]) {
                    right -= 1;
                }
                // Move to the next unique item
                left += 1;
                right -= 1;
            } else if (total < 0) {
                left += 1;

            } else {
                right -= 1;
            }
        }

    }
    return result;
};

想不明白的时候可以画图去看看指针移动的过程,好头脑也不如画个图。留下一个问题,那如果是四数之和呢,又怎么解决呢?

posted @ 2024-03-31 22:30  freephp  阅读(52)  评论(0编辑  收藏  举报