[코테] 1. Two Sum
My Solution
1
2
3
4
5
6
7
8
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
for i in range(n - 1) :
for j in range(i + 1, n) :
if nums[i] + nums[j] == target:
return [i, j]
return []
이렇게 풀었지만 하나씩 그냥 다 더하는 방법이라 좀 무식한것같다
Other Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
numMap = {}
n = len(nums)
for i in range(n):
numMap[nums[i]] = i
for i in range(n):
complement = target - nums[i]
if complement in numMap and numMap[complement] != i:
return [i, numMap[complement]]
return []
이거는 hash table에 num들 다 넣고 보수를 찾는다
complement를 찾을때 처음 보수가 없더라도 i가 range(n)에서 돌아가기 때문에 상관없이 다 검색한다
This post is licensed under CC BY 4.0 by the author.