File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution :
2+ def twoSum (self , nums : list [int ], target : int ) -> list [int ]:
3+ """
4+ ๋ฆฌ์คํธ์์ ๋ ์ซ์์ ํฉ์ด target์ด ๋๋ ๊ฒฝ์ฐ๊ฐ ์์ผ๋ฉด, ๊ทธ ๋ ์ซ์์ ์ธ๋ฑ์ค๋ฅผ ๋ฐํํ๋ ํจ์
5+
6+ ๋ฐฉ๋ฒ:
7+ 1. ๋ฆฌ์คํธ๋ฅผ ์ํํ๋ฉด์, ๊ฐ ์ซ์์์ target์ ๋ง๋ค๊ธฐ ์ํ ๋๋จธ์ง ์ซ์๊ฐ ์๋์ง ๋ชจ๋ ์ํ (brute-force); o(n^2) ์๊ฐ๋ณต์ก๋
8+ 2. ๋ฆฌ์คํธ๋ฅผ ์ํํ๋ฉด์, ๊ฐ ์ซ์์์ target์ ๋ง๋ค๊ธฐ ์ํ ๋๋จธ์ง ์ซ์๊ฐ ์๋์ง search (binary search); o(nlogn) ์๊ฐ๋ณต์ก๋
9+ 3. ๋ฆฌ์คํธ๋ฅผ ์ํํ๋ฉด์, ๊ฐ ์ซ์๋ฅผ dict์ ์ ์ฅํ์ฌ (key=์ซ์, value=์ธ๋ฑ์ค),
10+ target์ ๋ง๋ค๊ธฐ ์ํ ๋๋จธ์ง ์ซ์๋ฅผ dict์์ search; o(n) ์๊ฐ๋ณต์ก๋ -> PICK!
11+
12+ * ๋ต์ด ํญ์ ์กด์ฌํ๋ค๋ ๊ฐ์ ํ์ ๋ฌธ์ ๋ฅผ ํ์ด.
13+ * ๋ฆฌ์คํธ์ ๊ธธ์ด๊ฐ 2 ์ดํ์ธ ๊ฒฝ์ฐ, ๋ ์ซ์์ ํฉ์ด target์ด ๋๋ ๊ฒฝ์ฐ๊ฐ ํญ์ ์กด์ฌํ๋ฏ๋ก [0, 1]์ ๋ฐํํ๋ค.
14+
15+ Args:
16+ nums (list[int]): ์ค๋ณต์ ํฌํจํ ์ ์ ๋ฐฐ์ด
17+ target (int): ์ฐพ์์ผ ํ๋ ๋ ์ซ์์ ํฉ
18+
19+ Returns:
20+ list[int]: ์ฐพ์๋ธ ๋ ์ซ์์ ์ธ๋ฑ์ค
21+ """
22+ if len (nums ) <= 2 :
23+ return [0 , 1 ]
24+ seen = dict ()
25+ for i , num in enumerate (nums ):
26+ remain = target - num
27+ if remain in seen :
28+ return [seen [remain ], i ]
29+ seen [num ] = i
You canโt perform that action at this time.
0 commit comments