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)