forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSeoya0512.py
More file actions
47 lines (41 loc) ยท 1.88 KB
/
Seoya0512.py
File metadata and controls
47 lines (41 loc) ยท 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'''
Approach:
์ฃผ์ด์ง ๋ฐฐ์ด์ ๋ ๋ฒ ์ํํ๋ฉฐ ๋ชจ๋ ๊ฐ๋ฅํ ์์ ๊ฒ์ฌํฉ๋๋ค.
๊ฐ ์์์ ๋ํด ์ดํ์ ์์๋ค๊ณผ์ ํฉ์ด target๊ณผ ๊ฐ์์ง ๋น๊ตํ์ฌ ์ผ์นํ๋ ๊ฒฝ์ฐ ์ธ๋ฑ์ค๋ฅผ ๋ฐํํฉ๋๋ค.
Time Complexity:
O(nยฒ)
- Outer Loop์์ n๋ฒ ๋ฐ๋ณต
- Inner Loop์์ ๊ฐ idx๋ง๋ค ์ต์ n-1๋ฒ ๋ฐ๋ณต
Space Complexity:
O(1)
- ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ๊ธฐ ์ํด ์์ ๊ฐ์ ํ์๋ก ํ์ง๋ง, ์
๋ ฅ๊ฐ์ ํฌํค์ ๋น๋กํ ์๋ก์ด ๊ณต๊ฐ ๋ถ์
'''
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for idx, xnum in enumerate(nums):
for jdx in range(idx + 1, len(nums)):
if (xnum + nums[jdx]) == target:
return [idx, jdx]
return []
'''
(๊ฐ์ )
Approach:
โYou may assume that each input would have exactly one solution, and you may not use the same element twice.โ
๋ผ๋ ๋ฌธ๊ตฌ์์ ํญ์ ์ ๋ต์ด ์กด์ฌํ๋ฉฐ ๊ฐ์ ์์๋ฅผ ์ค๋ณต ์ฌ์ฉํ ์ ์์์ ์ ์ ์์ต๋๋ค.
์ด๋ฅผ ๋ฐํ์ผ๋ก ๊ฐ ์์ num์ ๋ํด (target - num)์ด ์ด์ ์ ๋ฑ์ฅํ ์ ์ด ์๋์ง๋ฅผ ํด์๋งต์ ์ด์ฉํด ๋น ๋ฅด๊ฒ ํ์ธํ๋๋ก ๊ฐ์ ํ์ต๋๋ค.
์ฆ, ์ค๋ณต์ด ์๊ณ ๋ต์ด ๋ฐ๋์ ์กด์ฌํ๋ค๋ ์กฐ๊ฑด ์๋์์, inner loop ์์ด ๋ฐ๋ก ์ฐพ๊ธฐ ์ํด ๋์
๋๋ฆฌ๋ฅผ ์ฌ์ฉํ ๊ฒ์
๋๋ค.
Time Complexity:
O(n)
- ๋ฆฌ์คํธ๋ฅผ ํ ๋ฒ ์ํํ๋ฉด์ ๋์
๋๋ฆฌ๋ฅผ ์ฑ์ ๋ฃ๋ ๋ฐ ๊ฑธ๋ฆฌ๋ ์ ์ฒด ์๊ฐ
Space Complexity:
O(n)
- ํด์๋งต์ key-value ์์ผ๋ก ์ ์ฅ๋๋ ๊ณต๊ฐ
'''
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash_map = {}
for i, num in enumerate(nums):
diff = target - num
if diff in hash_map:
return [hash_map[diff], i]
hash_map[num] = i