[코테] 704. Binary Search
My Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def search(self, nums: List[int], target: int) -> int:
numMap = {}
n = len(nums)
for i in range(n):
numMap[nums[i]] = i
for i in range(n):
if target in numMap:
return numMap[target]
else:
return (-1)
이렇게 풀기는 했지만 원래는 Binary Search 를 사용해서 풀어야 함
풀리긴 하지만 시간복잡도가 더 좋지않음
Binary Search Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
This post is licensed under CC BY 4.0 by the author.