Skip to content

Commit 6df2844

Browse files
committed
feat: add "Two Sum" solution
1 parent e4a3b68 commit 6df2844

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
# Constraints
3+
4+
2 <= nums.length <= 10^4
5+
-10^9 <= nums[i] <= 10^9
6+
-10^9 <= target <= 10^9
7+
8+
๊ฐ™์€ ์ˆซ์ž ๋‘๋ฒˆ ์‚ฌ์šฉ X
9+
10+
# Time Complexity: O(n)
11+
12+
O(n^2) ์œผ๋กœ๋„ ๊ฐ€๋Šฅ์€ ํ•˜์ง€๋งŒ, ๋ฌธ์ œ์—์„œ ์ด๊ฑฐ๋ณด๋‹ค ๋” ์ ์€ ์‹œ๊ฐ„๋ณต์žก๋„๋กœ ํ’€ ์ˆ˜๋„ ์žˆ๋‹ค๋Š” ๋ง์ด ์กด์žฌ
13+
๋ฐฐ์—ด ์ˆœํšŒํ•˜๋ฉฐ
14+
์ฒซ ์›์†Œ๋Š” target - n ์„ ํ•œ ๊ฐ’์„ set์— ๋„ฃ์–ด๋‘๊ธฐ
15+
๋‹ค์Œ ์›์†Œ๋ถ€ํ„ฐ๋Š” ํ•ด๋‹น ๊ฐ’์ด set์— ์žˆ๋Š”์ง€ ์ฒดํฌ
16+
์—†๋‹ค๋ฉด target - n ๋„ฃ๊ธฐ
17+
18+
๊ทผ๋ฐ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ์›์†Œ์˜ "idx" ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผํ•จ
19+
-> set๋Œ€์‹  dict๋ฅผ ์จ์„œ,
20+
-> dict[value] = idx๋กœ ๊ตฌ์„ฑ
21+
-> dict[7] = 0
22+
-> ๋ฐฐ์—ด 7 ์˜ค๋ฉด, ํ˜„์žฌ idx๋ž‘ ๊ธฐ์กด idx ๊ฐ€์ ธ์˜ค๊ธฐ ๊ฐ€๋Šฅ!
23+
24+
# Space Complexity: O(n)
25+
26+
๋ฐฐ์—ด ์›์†Œ ๊ฐœ์ˆ˜๋งŒํผ target - n ๊ฐ’์ด ๋“ค์–ด๊ฐˆ set ํฌ๊ธฐ๊ฐ€ ๊ฒฐ์ •๋จ
27+
28+
"""
29+
30+
31+
class Solution:
32+
def twoSum(self, nums: List[int], target: int) -> List[int]:
33+
ret = []
34+
diffDict = dict()
35+
36+
diffDict[target - nums[0]] = 0
37+
38+
for i in range(1, len(nums)):
39+
if nums[i] in diffDict:
40+
ret.append(diffDict[nums[i]])
41+
ret.append(i)
42+
return ret
43+
44+
else:
45+
diffDict[target - nums[i]] = i

0 commit comments

Comments
ย (0)