[leetcode]15.3Sum

Mayton·2022년 6월 12일
0

Coding-Test

목록 보기
5/37
post-thumbnail

문제

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]]
  • Example 2:

    	- Input: nums = []
    	- Output: []
  • Example 3:

    	- Input: nums = [0]
    	- Output: []

제한사항

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

풀이1

function solution(nums) {
   if (nums.length < 3) return [];
   const array = combination(nums, 3);
   console.log(array);
   const result = [];
   for (const [i, j, k] of array) {
   if (i + j + k === 0) {
       result.push([i, j, k]);
     }
   }
   return result;
 }

 function combination(arr, n) {
   if (n === 1) return arr.map((v) => [v]);

   let result = [];
   arr.forEach((fixed, idx, arr) => {
     const rest = arr.slice(idx + 1);
     const combine = combination(rest, n - 1);
     const combins = combine.map((v) => [fixed, ...v]);
     result.push(...combins);
   });
   return result;
 }

세개의 수를 combination을 통해 임의로 뽑아 합이 0이되면 result array에 추가하는 방식으로 정답을 구현하고자 처음 생각했다. 하지만 제한사항으로 num.length <=3000이었기 때문에 combination만 O(n2)이기 때문에 구현 할 수 없었다. 그렇다면 O(n2) 정도 사용하는 방법을 통해 정답을 구해야 했다.

정답

function solution(nums) {
  let resultArr = [];
  const sortedArr = nums.sort((a, b) => a - b);
  for (let i = 0; i < sortedArr.length - 2; i++) {
    if (sortedArr[i] > 0) {
      break;
    }
    if (i > 0 && sortedArr[i] === sortedArr[i - 1]) {
      continue;
    }
    let left = i + 1;
    let right = sortedArr.length - 1;
    while (left < right) {
      const sum = sortedArr[i] + sortedArr[left] + sortedArr[right];

      if (sum < 0) {
        left++;
      } else if (sum > 0) {
        right--;
      } else {
        resultArr.push([sortedArr[i], sortedArr[left], sortedArr[right]]);
        while (left < right && sortedArr[left] == sortedArr[left + 1]) {
          left++;
        }
        while (left < right && sortedArr[right == sortedArr[right - 1]]) {
          right--;
        }
        left++;
        right--;
      }
    }
}
return resultArr;
}

오름차순으로 정렬된 sortedArr에서 시작한다.
가장 작은 수를 기준으로 하여 시작하고, 기준점이후로 가장작은 수 left, 가장 큰 수를 right 으로 지정하여, 합 sum이 target(0)보다 크다면, 작은수를 left++를 통해 크게, sum이 target(0)보다 작다면 큰수 right--를 통해 작게 만든다. 같은 수가 포함되어 있을 수 있기때문에 left+1가 left와, 혹은 right 이 right-1과 같을 때는 그 index를 뛰어 넘도록 만든다.

추가사항

비슷한 문제로 3SumClosest가 있고, 같은 방식으로 풀이한다면, 쉽게 풀 수 있었다. 제한사항의 크기와, 내가 사용하고 있는 풀이가 O(n)의 크기가 얼마나 되어 계산을 할 수 있는지를 풀이를 생각할 때부터 생각해서, 괜한 풀이를 끝까지 풀어놓고 다시 또 시작하는 일이 없어야겠다.

profile
개발 취준생

0개의 댓글