Skip to content

Commit 601e211

Browse files
committed
Add 2nd solution to Two Sum problem
1 parent 491edf0 commit 601e211

File tree

1 file changed

+36
-13
lines changed

1 file changed

+36
-13
lines changed

โ€Žtwo-sum/KwonNayeon.pyโ€Ž

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
11
"""
2+
Problem: Two Sum
3+
24
Constraints:
3-
- 2 <= nums.length <= 10^4
4-
- -10^9 <= nums[i] <= 10^9
5-
- -10^9 <= target <= 10^9
6-
- Only one valid answer exists.
7-
5+
- 2 <= nums.length <= 10^4
6+
- -10^9 <= nums[i] <= 10^9
7+
- -10^9 <= target <= 10^9
8+
- Only one valid answer exists.
9+
10+
<Solution 1>
811
Time Complexity: O(nยฒ)
9-
- ์ค‘์ฒฉ ๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ
10-
- ์ฒซ ๋ฒˆ์งธ ๋ฐ˜๋ณต๋ฌธ: n๋ฒˆ
11-
- ๊ฐ๊ฐ์— ๋Œ€ํ•ด ๋‘ ๋ฒˆ์งธ ๋ฐ˜๋ณต๋ฌธ: n-1, n-2, ... 1๋ฒˆ
12-
- ๋”ฐ๋ผ์„œ ์ด ์—ฐ์‚ฐ ํšŸ์ˆ˜๋Š” n * (n-1)/2๋กœ O(nยฒ)
12+
- ์ค‘์ฒฉ ๋ฐ˜๋ณต๋ฌธ ์‚ฌ์šฉ
13+
- ์ฒซ ๋ฒˆ์งธ ๋ฐ˜๋ณต๋ฌธ: n๋ฒˆ
14+
- ๊ฐ๊ฐ์— ๋Œ€ํ•œ ๋‘ ๋ฒˆ์งธ ๋ฐ˜๋ณต๋ฌธ: n-1, n-2, ... 1๋ฒˆ
15+
- ์ด ์—ฐ์‚ฐ ํšŸ์ˆ˜: n * (n-1)/2
1316
1417
Space Complexity: O(1)
15-
- ์ถ”๊ฐ€ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Œ
16-
- result ๋ฆฌ์ŠคํŠธ๋Š” ํ•ญ์ƒ ํฌ๊ธฐ๊ฐ€ 2๋กœ ๊ณ ์ •
18+
- ์ถ”๊ฐ€ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Œ
19+
- result๋Š” ํ•ญ์ƒ ํฌ๊ธฐ๊ฐ€ 2๋กœ ๊ณ ์ •๋จ
1720
"""
18-
# Solution 1
1921
class Solution:
2022
def twoSum(self, nums: List[int], target: int) -> List[int]:
2123
result = []
@@ -25,5 +27,26 @@ def twoSum(self, nums: List[int], target: int) -> List[int]:
2527
if nums[j] == target - nums[i]:
2628
return [i, j]
2729

28-
# Solution 2
30+
"""
31+
<Solution 2: ํ•ด์‹œ ํ…Œ์ด๋ธ” ํ™œ์šฉ>
32+
Time Complexity: O(n)
33+
- ๋ฐฐ์—ด์„ ํ•œ ๋ฒˆ๋งŒ ์ˆœํšŒ
34+
35+
Space Complexity: O(n)
36+
- ์ตœ์•…์˜ ๊ฒฝ์šฐ ํ•ด์‹œ ํ…Œ์ด๋ธ”์— n๊ฐœ๋ฅผ ์ €์žฅ
37+
- ์ถ”๊ฐ€ ๊ณต๊ฐ„์ด ์ž…๋ ฅ ํฌ๊ธฐ์— ๋น„๋ก€
38+
"""
39+
class Solution:
40+
def twoSum(self, nums: List[int], target: int) -> List[int]:
41+
seen = {}
42+
43+
for i, num in enumerate(nums):
44+
complement = target - num
45+
46+
if complement in seen:
47+
return [seen[complement], i]
48+
49+
seen[num] = i
50+
51+
return []
2952

0 commit comments

Comments
ย (0)