Skip to content

Commit de9f641

Browse files
committed
solve(w01): 1. Two Sum
1 parent fed0fd4 commit de9f641

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# https://leetcode.com/problems/two-sum/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def twoSum(self, nums: List[int], target: int) -> List[int]:
7+
"""
8+
[Complexity]
9+
- TC: O(n)
10+
- SC: O(n)
11+
12+
[Approach]
13+
ํ•ญ์ƒ ํ•˜๋‚˜์˜ ์ •๋‹ต์ด ์กด์žฌํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ๋ณต์žก๋„๋ฅผ O(n^2)๋ณด๋‹ค ์ค„์ด๊ธฐ ์œ„ํ•ด์„œ๋Š” hash map์— (target - num) ๊ฐ’์„ ์ €์žฅํ•จ์œผ๋กœ์จ
14+
ํ˜„์žฌ ๋ณด๊ณ ์žˆ๋Š” ๊ฐ’๊ณผ ๋”ํ–ˆ์„ ๋•Œ target์ด ๋˜๋Š” ๊ฐ’์„ ์ฐพ๋Š” ๊ณผ์ •์— ๋“œ๋Š” ๋ณต์žก๋„๋ฅผ O(1)์œผ๋กœ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.
15+
1. nums๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ, hash map์˜ key์— ํ˜„์žฌ ๊ฐ’์ด ์กด์žฌํ•˜๋Š”์ง€(= ํ˜„์žฌ ๊ฐ’๊ณผ ๋”ํ–ˆ์„ ๋•Œ target์ด ๋˜๋Š” ๊ฐ’์ด ์žˆ๋Š”์ง€) ํ™•์ธํ•œ๋‹ค.
16+
2. ์กด์žฌํ•œ๋‹ค๋ฉด, ํ˜„์žฌ ๊ฐ’์˜ index์™€ hash map์˜ value์— ๊ธฐ๋ก๋˜์–ด ์žˆ๋Š” index๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
17+
3. ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด, hash map์— {(target - num): index}๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.
18+
"""
19+
20+
remains = dict()
21+
22+
for i, num in enumerate(nums):
23+
if num in remains:
24+
return [remains[num], i]
25+
26+
remains[target - num] = i

0 commit comments

Comments
ย (0)