Skip to content

Commit bd23824

Browse files
committed
feat: week1-two sum
1 parent 269536a commit bd23824

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

β€Žtwo-sum/Seoya0512.pyβ€Ž

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
'''
2+
Approach:
3+
μ£Όμ–΄μ§„ 배열을 두 번 μˆœνšŒν•˜λ©° λͺ¨λ“  κ°€λŠ₯ν•œ μŒμ„ κ²€μ‚¬ν•©λ‹ˆλ‹€.
4+
각 μ›μ†Œμ— λŒ€ν•΄ μ΄ν›„μ˜ μ›μ†Œλ“€κ³Όμ˜ 합이 targetκ³Ό 같은지 λΉ„κ΅ν•˜μ—¬ μΌμΉ˜ν•˜λŠ” 경우 인덱슀λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
5+
6+
Time Complexity:
7+
O(nΒ²)
8+
- Outer Loopμ—μ„œ n번 반볡
9+
- Inner Loopμ—μ„œ 각 idxλ§ˆλ‹€ μ΅œμ†Œ n-1번 반볡
10+
11+
Space Complexity:
12+
O(1)
13+
- κ²°κ³Όλ₯Ό μ €μž₯ν•˜κΈ° μœ„ν•΄ μƒμˆ˜ 값을 ν•„μš”λ‘œ ν•˜μ§€λ§Œ, μž…λ ₯κ°’μ˜ 크킀에 λΉ„λ‘€ν•œ μƒˆλ‘œμš΄ 곡간 λΆˆμš”
14+
'''
15+
16+
class Solution:
17+
def twoSum(self, nums: List[int], target: int) -> List[int]:
18+
for idx, xnum in enumerate(nums):
19+
for jdx in range(idx + 1, len(nums)):
20+
if (xnum + nums[jdx]) == target:
21+
return [idx, jdx]
22+
return []
23+
24+
'''
25+
(κ°œμ„ )
26+
Approach:
27+
β€œYou may assume that each input would have exactly one solution, and you may not use the same element twice.”
28+
λΌλŠ” λ¬Έκ΅¬μ—μ„œ 항상 정닡이 μ‘΄μž¬ν•˜λ©° 같은 μ›μ†Œλ₯Ό 쀑볡 μ‚¬μš©ν•  수 μ—†μŒμ„ μ•Œ 수 μžˆμŠ΅λ‹ˆλ‹€.
29+
이λ₯Ό λ°”νƒ•μœΌλ‘œ 각 μ›μ†Œ num에 λŒ€ν•΄ (target - num)이 이전에 λ“±μž₯ν•œ 적이 μžˆλŠ”μ§€λ₯Ό ν•΄μ‹œλ§΅μ„ μ΄μš©ν•΄ λΉ λ₯΄κ²Œ ν™•μΈν•˜λ„λ‘ κ°œμ„ ν–ˆμŠ΅λ‹ˆλ‹€.
30+
즉, 쀑볡이 μ—†κ³  닡이 λ°˜λ“œμ‹œ μ‘΄μž¬ν•œλ‹€λŠ” 쑰건 μ•„λž˜μ—μ„œ, inner loop 없이 λ°”λ‘œ μ°ΎκΈ° μœ„ν•΄ λ”•μ…”λ„ˆλ¦¬λ₯Ό μ‚¬μš©ν•˜ κ²ƒμž…λ‹ˆλ‹€.
31+
32+
Time Complexity:
33+
O(n)
34+
- 리슀트λ₯Ό ν•œ 번 μˆœνšŒν•˜λ©΄μ„œ λ”•μ…”λ„ˆλ¦¬λ₯Ό μ±„μ›Œ λ„£λŠ” 데 κ±Έλ¦¬λŠ” 전체 μ‹œκ°„
35+
36+
Space Complexity:
37+
O(n)
38+
- ν•΄μ‹œλ§΅μ— key-value 쌍으둜 μ €μž₯λ˜λŠ” 곡간
39+
'''
40+
class Solution:
41+
def twoSum(self, nums: List[int], target: int) -> List[int]:
42+
hash_map = {}
43+
for i, num in enumerate(nums):
44+
diff = target - num
45+
if diff in hash_map:
46+
return [hash_map[diff], i]
47+
hash_map[num] = i
48+
49+

0 commit comments

Comments
Β (0)