| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
- RxJS 에러 처리
- RxJS 멀티캐스팅
- useMemo 성능 최적화
- 달래스터디
- React useMemo 사용법
- Climbing Stairs
- useCallback 성능 최적화
- RxJS 생성 오퍼레이터
- React 리렌더링 최적화
- Blind75
- 개발자커뮤니케이션
- 협업문화
- 자바스크립트 고차 함수 vs Observable
- RxJS 오퍼레이터
- RxJS 마블 다이어그램
- React useCallback 사용법
- DaleStudy
- RxJS 변환 오퍼레이터
- 알고리즘
- leedcode
- contains duplicate
- 스쿼드조직
- leetcode
- RxJS 함수형 프로그래밍
- Observable vs Array
- 알고리즘스터디
- React useEffect 안티패턴
- React 성능 최적화 방법
- React hooks 남용 사례
- RxJS 결합 오퍼레이터
- Today
- Total
수쿵의 IT월드
DaleStudy | Leetcode Study 2주차 - 3Sum 본문

문제
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
};