Skip to content

Commit 044b91e

Browse files
committed
feat: twoSum solution
1 parent eb6f9b6 commit 044b91e

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

โ€Žtwo-sum/rara-record.pyโ€Ž

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from typing import List
2+
3+
"""
4+
๋ฌธ์ œ ์„ค๋ช…:
5+
nums์—์„œ ๋‘ ์ˆ˜๋ฅผ ๋”ํ•ด target์ด ๋˜๋Š” ๋‘ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์•„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ
6+
๊ฐ™์€ ์›์†Œ๋ฅผ ๋‘ ๋ฒˆ ์“ธ ์ˆ˜ ์—†์Œ
7+
์ฐพ์•ผ์•ผํ•˜๋Š” ๊ฐ’: taget - ํ˜„์žฌ ์ˆซ์ž = ๋”ํ•ด์„œ target์ด ๋˜๋Š” ๊ฐ’
8+
9+
nums = [2,7,11,15], target = 9
10+
{
11+
2: 0, (value: index)
12+
7: 1,
13+
11: 2,
14+
15: 3,
15+
}
16+
17+
1. nums๋ฅผ ํ•œ ๋ฒˆ ์ˆœํšŒํ•˜๋ฉฐ ๊ฐ ์ˆซ์ž์™€ ์ธ๋ฑ์Šค๋ฅผ ๋”•์…”๋„ˆ๋ฆฌ์— ์ €์žฅ
18+
2. ๋‹ค์‹œ nums๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ, target - ํ˜„์žฌ ์ˆซ์ž๊ฐ€ ๋”•์…”๋„ˆ๋ฆฌ์— ์žˆ๊ณ  ์ธ๋ฑ์Šค๊ฐ€ ๋‹ค๋ฅด๋ฉด ์ •๋‹ต ์Œ์„ ๋ฐ˜ํ™˜
19+
"""
20+
21+
22+
class Solution:
23+
def twoSum(self, nums: List[int], target: int) -> List[int]:
24+
dic = {}
25+
26+
for key, value in enumerate(nums):
27+
dic[value] = key
28+
29+
# ๋‹ค์‹œ nums๋ฅผ ์ˆœํšŒ
30+
for key, value in enumerate(nums):
31+
match = target - value
32+
33+
# ๊ฐ™์€ ์›์†Œ๋ฅผ ๋‘๋ฒˆ ์“ธ ์ˆ˜ ์—†๋‹ค.
34+
if (match in dic) and key != dic[match]:
35+
return [key, dic[match]]
36+
37+
"""
38+
์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
39+
- ๋ฆฌ์ŠคํŠธ๋ฅผ ๋‘ ๋ฒˆ ์ˆœํšŒํ•˜์ง€๋งŒ ๊ฐ๊ฐ O(n)์ด ์†Œ์š”๋˜๋ฏ€๋กœ, ์ด ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n)
40+
๊ณต๊ฐ„ ๋ณต์žก๋„: O(n)
41+
- ์ž…๋ ฅ ํฌ๊ธฐ๊ฐ€ n์ด๋ผ๋ฉด ๋”•์…”๋„ˆ๋ฆฌ์˜ ํฌ๊ธฐ๋„ ์ตœ๋Œ€ n
42+
"""
43+

0 commit comments

Comments
ย (0)