forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYOOHYOJEONG.py
More file actions
24 lines (18 loc) ยท 822 Bytes
/
YOOHYOJEONG.py
File metadata and controls
24 lines (18 loc) ยท 822 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# https://leetcode.com/problems/two-sum/description/
# class Solution(object):
# def twoSum(self, nums, target):
# for i in range(len(nums)):
# for j in range(len(nums)):
# if nums[i]+nums[j] == target:
# if i != j:
# return [i, j]
# > ํด๋น ๋ฐฉ์ ์ฌ์ฉ ์ ์๊ฐ ๋ณต์ก๋๊ฐ O(nยฒ)์ด๋ผ ๊ฐ์ ์ ํด ๋ณด๊ณ ์ ์๋ ์๋ฃจ์
์ผ๋ก ์ฌํ์ด ์งํ
class Solution(object):
def twoSum(self, nums, target):
seen = {}
for i, num in enumerate(nums):
diff = target - num
if diff in seen:
return [seen[diff], i]
seen[num] = i
# index๋ฅผ ๊ธฐ์ตํ๋๋ก ํ๋ฉด ๋ฐ๋ณต๋ฌธ ํ๋ฒ O(n), ๋์
๋๋ฆฌ ์กฐํ ํ๊ท O(1)๋ก ์ ์ฒด O(n)์ด ๋จ