I. Title Description:

Given an array nums containing n integers, determine if there are three elements a, B, and c in nums such that a + b + c = 0. Please find all the triples that sum to 0 and are not repeated. Note: Repeated triples cannot be included in the answer. Example 1:

Input: nums = [1, 2, 1, 4] output: [[1, 1, 2], [1, 1]]

Example 2:

Nums = [] Output: []

Ii. Analysis of Ideas:

  1. Sort an array
  2. Fixed a number of nums [I], then use pointer to around nums behind [I] at both ends, respectively is nums [L] and nums [R], and then judge whether the sum of three Numbers is equal to zero, if is zero is added to the collection
  3. If nums[I] == nums[i-1] causes a repeat, skip
  4. If nums[L] == nums[L + 1], sum == 0, nums[L + 1], nums[L + 1], nums[L + 1], nums[L + 1], nums[L + 1
  5. When sum == 0, nums[R] == nums[R – 1], R++ should be skipped

Iii. AC Code:

/ * * *@param {number[]} nums
 * @return {number[][]}* /
var threeSum = function(nums) {
    let list = [], len = nums.length;
    nums.sort((a, b) = > a - b); / / sorting
    for(let i = 0; i < len; i++) {if(nums[i] > 0) break;
        if(nums[i] === nums[i -1]) continue;
        let L = i + 1, R = len -1;
        while(L < R) {
            let sum = nums[i] + nums[L] + nums[R];
            if(sum === 0) {
                list.push([nums[i], nums[L], nums[R]]);
                while(L < R && nums[L] === nums[L + 1]) L++;
                while(L < R && nums[R] === nums[R - 1]) R--;
                L++;
                R--;
            } else if(sum < 0) {
                L++
            } else {
                R--
            }
        }
    }
    return list;
};
Copy the code

Iv. Summary:

Execution result: By displaying details Execution time: 152 ms, beat 94.89% of users in all JavaScript commits memory consumption: 48.1 MB, beat 31.88% of users in all JavaScript commits

The second day, the workers refueling… This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign