-
leetCode - 3sum프로그래밍/algorithm 2021. 7. 20. 11:41
문제
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: []
Constraints:
- 0 <= nums.length <= 3000
- -105 <= nums[i] <= 105
풀이
1.
const threeSum = function (nums) { let result = []; for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { for (let c = j + 1; c < nums.length; c++) { if (nums[i] + nums[j] + nums[c] === 0) { result.push([nums[i], nums[j], nums[c]]); } } } } const sortedResult = result.map(array => array.sort()); result = [...new Set(sortedResult.map(JSON.stringify))].map(JSON.parse); return result; };
가장 쉽게 생각할 수 있는 방법. 반복문 세개 돌리면 됨. 하지만 시간초과 ㅜㅜ
2.
function threeSum(nums) { let result = []; nums.sort((a, b) => a - b); for (let i = 0; i < nums.length; i++) { let low = i + 1, high = nums.length - 1, sum = 0; while (low < high) { sum = nums[i] + nums[low] + nums[high]; if (sum === 0) { result.push([nums[i], nums[low], nums[high]]); while (nums[low] === nums[low + 1]) low++; while (nums[high] === nums[high - 1]) high--; low++; high--; } else if (sum < 0) low++; else high--; } while (nums[i] === nums[i + 1]) i++; } console.log(result); }
이 풀이법도 반복문안에 여러개의 반복문이 있어 지저분하긴 하지만, 1번보다는 훨씬 빠름
'프로그래밍 > algorithm' 카테고리의 다른 글
leetCode - Letter Combinations of a Phone Number(backtracking) (0) 2021.07.22 leetCode - 3Sum Closest (0) 2021.07.21 leetCode - Integer to Roman (0) 2021.07.20 leetCode - Container With Most Water (0) 2021.07.20 leetCode - Regular Expression Matching (0) 2021.07.19