Skip to content

Commit 303055a

Browse files
committed
feat: implement twoSum function to find indices of two numbers that add up to target
1 parent 88dc958 commit 303055a

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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

0 commit comments

Comments
ย (0)