수쿵의 IT월드

DaleStudy | Leetcode Study 2주차 - 3Sum 본문

알고리즘

DaleStudy | Leetcode Study 2주차 - 3Sum

수쿵IT 2025. 7. 30. 23:12

Leetcode Study

문제

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.

 

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.

Constraints:

  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5

 

풀이

보통 더해서 원하는 값이 나온다는 문제 중, 인덱스의 위치가 필요한 문제가 아니라면 정렬을 먼저 하고 보는게 편하다. 그 뒤에 3개의 값을 구하는 것이기 때문에 left와 right 두 개를 두고, 반복문을 한 번 돌려주면 3개의 포인터를 가질 수 있다. 여기서 나는 중복이 되는 배열까지는 구할 수 있었는데, 중복을 제거하는 부분은 해설을 참고하긴 했다. 

 

예를 들어 [-1,0,1,2,-1,-4] 이 배열이 주어졌을 때, 우리가 찾을 수 있는 배열은 [-1,-1, 2], [-1,0,1], [-1,0,1] 인데 이 이유는 배열 안에 1이 2개가 포함되어 있기 때문이다. 하지만 문제에서 원하는 답은 중복이 사라진 [-1,-1, 2], [-1,0,1] 이 배열 2개이다. 

 

그 부분을 구하기 위해 내가 추가한 코드는 아래의 코드인데, 이 코드는 다음 원소와 지금 원소가 동일한 값이면 하나더 원소를 더해주는 역할을 한다. 이 코드를 통해서 중복이 없는 코드를 구할 수 있는 것이다.

while (left < right && nums[left] === nums[left + 1]) left++;
while (left < right && nums[right] === nums[right - 1]) right--;

 

 

사실 이해는 했지만, 일주일 뒤에 다시 풀어보라고 하면 다시 풀 수 있을지가 미지수이긴 하다

function threeSum(nums: number[]): number[][] {
    nums.sort((a: number, b: number) => a - b);
    const results: [number, number, number][] = [];

    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) {
            const current = nums[i] + nums[left] + nums[right];
            if (current === 0) {
                results.push([nums[i], nums[left], nums[right]]);

                while (left < right && nums[left] === nums[left + 1]) left++;
                while (left < right && nums[right] === nums[right - 1]) right--;

                left++;
                right--;
            } else if (current < 0) {
                left++;
            } else if (current > 0) {
                right--;
            }
        }
    }

    return results
};

 

 

Link: https://leetcode.com/problems/3sum/