[JS] 3Sum

2022. 8. 6. 13:57

🔒 문제 (LeetCode 15)

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Constraints:

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

 

🌊 입출력

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: 
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.

Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.

Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.

 


 

🔑 해결

🌌 알고리즘 - 투포인터

투포인터의 응용으로 3개의 포인터를 이용하는 문제로 정렬 후 포인터를 사용.

i는 왼쪽, k는 오른쪽, j는 그 사이 index.

i를 고정하고 세개의 합이 0(target)보다 작으면 j를 오른쪽으로 이동, 크면 k를 왼쪽으로 이동.

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    const result = [];
    
    if(nums.length < 3) return result;
    
    nums = nums.sort((a, b) => a - b); 
    let target = 0;
    
    for(let i = 0; i < nums.length - 2; i++) {
        if(nums[i] > target) break;
        
        if(i > 0 && nums[i] === nums[i-1]) continue;
        
        let j = i + 1;
        let k = nums.length - 1
        
        while(j < k) {
            let sum = nums[i] + nums[j] + nums[k];
            
            if(sum === target) {
                result.push([nums[i], nums[j], nums[k]]);
                
                while(nums[j] === nums[j + 1]) j++;
                while(nums[k] === nums[k - 1]) k--;
                j++;
                k--;
            } 
            else if(sum < target) j++;
            else k--;
        }
    }
    
    return result;
};

+ Recent posts