[Algorithm training - array] leetcode13. Sum of three numbers (js)

Topic link: leetcode-cn.com/problems/3s…

Topic description

Given an array nums containing n integers, determine if there are three elements a, b, c in nums such that a + b + c = 0? Please find all triples whose sum is 0 and does not repeat.

Note: Answers cannot contain duplicate triples.

  • Example 1:

Input: nums = [-1,0,1,2,-1,-4]

Output: [[-1,-1,2],[-1,0,1]]

  • Example 2:

Input: nums = []

output: []

  • hint:

0 <= nums.length <= 3000

-105 <= nums[i] <= 105

problem solving

Optimal solution: sort first, then use double pointer movement method, time complexity o(n)

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    // 对数组进行排序
    let arrSOrt = nums.sort((a,b) => a - b);
    // 结果数组
    let result = [];
    for (let i = 0; i<nums.length; i++) {
        // 去重
        if (i > 0 && arrSOrt[i] === arrSOrt [i - 1])
            continue;
        let left = i + 1;
        let right = nums.length - 1;
        while(left < right) {
            let sum = arrSOrt[i] + arrSOrt[left] + arrSOrt[right];
            if (sum === 0) {
                result.push([arrSOrt[i], arrSOrt[left], arrSOrt[right]]);
                // 去重
                while(left < right && arrSOrt[left] === arrSOrt[left+1]) left++;
                while(left < right && arrSOrt[right] === arrSOrt[right - 1]) right--;
                left++;
                right--;
            } else if (sum < 0) {
                left++;
            } else {
                right--;
            }
        }
    }
    return result;
};
复制代码

Summarize

This topic is easy to ignore and de-duplicate, and it is still a bit of a challenge to write it right at one time.

Algorithm practice github: github.com/mengmengzp/…

Guess you like

Origin juejin.im/post/7083805639805255716