LeetCode series 15. 3Sum (JavaScript)

Keywords: less

Q:

Title Link: 3Sum
First look at the requirements:
  Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

                          .

Analysis
It's impossible to solve by violence. At least one O(n3) solution is needed, so give up Because the result of this problem is closely related to the size of the elements, it will be easier to think of sorting the array and then solving it. After sorting, you need to consider how to find out all the "triplets" child element arrays? First loop to determine one, then select the first and last two of the remaining elements, and determine the pointer movement according to the size of the sum. Look at the code:

A:

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    var result = [];
    //Less than three elements, return null
    if(nums.length < 3){
        return result;
    }
    //Order first (from small to large)
    nums = nums.sort(function(a,b){return a-b})
    //Because it is in ascending order, if the first element is larger than 0, there must be no matching array
    if(nums > 0){
        return result;
    }
    for(var i = 0;i < nums.length - 2;i++){
        //Remove duplicate results
        if (i > 0 && nums[i] === nums[i - 1]) {
            continue;
        }
        var left = i+1;
        var right = nums.length - 1;
        while(left < right){
            var sum = nums[i] + nums[left] + nums[right];
            if(sum === 0){
                result.push([nums[i],nums[left],nums[right]])
                left++;
                right--;
                //Remove duplicate results and move the pointer directly to different elements
                while(left < right && nums[left] === nums[left - 1]){
                    left++;
                }
                while(left < right && nums[right] === nums[right + 1]){
                    right--;
                }
            }else if(sum > 0){
                right--;
            }else{
                left++;
            }
        }
    }
    return result;
};

                     .

Posted by r.smitherton on Wed, 01 Apr 2020 15:25:07 -0700