Leetcode - Medium - 15. 3Sum - Javascript

2022年1月23日 星期日

Leetcode - Medium - 15. 3Sum - Javascript


Medium

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != ji != 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]]

Example 2:

Input: nums = []
Output: []

Example 3:

Input: nums = [0]
Output: []

 

Constraints:

  • 0 <= nums.length <= 3000
  • -105 <= nums[i] <= 105

 


解題方向:
1. 需要先由小到大排序 array
2. 這題要透過 two point 方式解, 所以除了 a 是原點外, 要增加a左邊一個的 b, 與最右邊的 c
3. 當 array 小於 3 時就不需要比較
4. 如果排序後第一位大於 0, 也代表後面排序的數字不可能相加等於 0, 可跳過這一輪的 a
5. 如果 a 這一輪的數字與前一輪比過的數字一樣, 也可以跳過這一輪的 a
6. 相加 nums[a], nums[b], nums[c] 等於 0 就紀錄到 result, 並讓 b, c 往中間移動, 需注意 b與c下一個如果與前一個相同數字則跳過, 因為已經計算過
7. 如 nums[a], nums[b], nums[c] 不等於 0, 則判斷  nums[b] + nums[c] 是否大於或小於 -nums[a], 如果是就讓 b or c 指標往中間移動繼續下一個判斷


程式碼 :
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    let result = [];
    const numsLen = nums.length;
    
    if (numsLen < 3) { return result; }
    
    nums.sort((a,b) => a-b);

    for (let a = 0; a < numsLen; a++) {
        if(nums[a] > 0){    
           break;
        }
        
        if (a > 0 && nums[a] === nums[a-1]) {
            continue;
        }
        
        let b = a + 1;
        let c = numsLen - 1;
        const temp = -(nums[a]);
        
        while (b < c) {
            if (nums[a] + nums[b] + nums[c] === 0) {
                result.push([nums[a], nums[b], nums[c]]);
            
                while(b < c && nums[b] === nums[b+1]) b++;
                while(b < c && nums[c] === nums[c-1]) c--;
                b++;
                c--;
            }
            
            const twoPointSum = nums[b] + nums[c];
            
            if (twoPointSum > temp) {
                c--;
            } else if (twoPointSum < temp) {
                b++;
            }
        }
    }
    
    
    return result;
};



執行成果:





0 意見 :

張貼留言