Skip to content

Commit 5f75c01

Browse files
committed
Add detailed comments to 3sum solution
1 parent 2f629c2 commit 5f75c01

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

3sum/KwonNayeon.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,35 @@
33
1. 3 <= nums.length <= 3000
44
2. -10^5 <= nums[i] <= 10^5
55
6-
Time Complexity:
7-
- O(n^2) (정렬은 O(n log n), 이중 반복문은 O(n^2))
8-
Space Complexity:
9-
- O(n) (결과 리스트)
6+
Time Complexity: O(n^2)
7+
- 정렬은 O(n log n), 이중 반복문은 O(n^2)
8+
Space Complexity: O(n)
9+
- 결과 리스트를 저장하는 데 필요한 공간
10+
11+
풀이 방법:
12+
- 투 포인터를 활용하여 합이 0이 되는 세 수 조합 찾기
13+
- 배열 정렬: 투 포인터 사용 + 중복 처리 용이
14+
- for 루프: 첫 번째 숫자 선택 (len(nums)-2까지)
15+
- 중복된 첫 번째 숫자 건너뛰기
16+
- left, right 포인터 설정
17+
- while 루프: 두 포인터가 교차하지 않아야 함
18+
- sum = nums[i] + nums[left] + nums[right] 계산
19+
- sum == 0: 결과 추가, 중복 건너뛰기, 양쪽 포인터 이동
20+
- sum < 0: left 증가 (더 큰 값 필요)
21+
- sum > 0: right 감소 (더 작은 값 필요)
22+
- 최종 결과 반환
1023
"""
24+
# Brute-force: three nested loops → O(n^3)
25+
# Optimized: sort + two pointer → O(n^2)
1126

1227
class Solution:
1328
def threeSum(self, nums: List[int]) -> List[List[int]]:
29+
# Step 1: Sort the array
30+
# Step 2: Fix one number using for loop
31+
# Step 3: Use two pointers to find two other numbers
32+
# - if sum == 0: valid triplet
33+
# - if sum < 0: move left pointer
34+
# - if sum > 0: move right pointer
1435
nums.sort()
1536
result = []
1637

0 commit comments

Comments
 (0)