Topic describes

Their thinking

  1. If the number of elements is less than 3, return an empty array.
  2. Sort an array from smallest to largest.
  3. Define three Pointers: I,left, and right. Where I is the pointer to our fixed loop until nums. length-2, where left is the ratio of I +1 and right is the last digit each time the loop starts.
  4. Store when the sum of three numbers is equal to 0, less than 0, left++, greater than 0, right–.
  5. The other thing that’s really important to consider in this case is the problem of duplicate values, when the sum of three numbers is zero, if left++ is the same as left, then it’s a duplicate value, and you don’t need to add it, and the same thing happens if right– is the same as right, and, It’s still going to be less than right,right– it’s still going to be greater than left.

The problem solving code

var threeSum = function (nums) {
    // If the number of elements is less than 4, return an empty array
    if (nums.length < 3) {
        return [];
    }
    let res = [];
    let temp = [];
    nums.sort((num1, num2) = > num1 - num2);
    for (let i = 0; i < nums.length - 2; i++) {
        if (i > 0 && (nums[i] === nums[i - 1]) {continue;
        }
        let left = i + 1;
        let right = nums.length - 1;
        while (left < right) {
            if (nums[i] + nums[left] + nums[right] === 0) {
                if (nums[left] === nums[left + 1] && right > left+1) {
                    left++
                    continue;
                } else if (nums[right] === nums[right - 1] && right > left + 1) {
                    right--;
                    continue;
                }
                temp.push(nums[i]);
                temp.push(nums[left]);
                temp.push(nums[right]);
                res.push(temp);
                temp = [];
                left++
            } else if (nums[i] + nums[left] + nums[right] < 0) {
                left++;
            } else{ right--; }}}return res
};
Copy the code

revelation

  • Learn how to fix one pointer and move the other two to solve problems.