File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
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
You canโt perform that action at this time.
0 commit comments