# 704. Binary Search

하나·2023년 3월 26일
0

## 코딩테스트

목록 보기
12/16

https://leetcode.com/problems/binary-search/?envType=study-plan&id=algorithm-i

# target 을 nums 에서 찾는 문제
# 존재하면 return index, 없으면 -1

# class Solution:
#     def search(self, nums: List[int], target: int) -> int:

#         left = nums[:len(nums)//2] # nums[0:3] -1,0,3
#         right = nums[len(nums)//2:] # nums[3:] 5,9,12

#         if target in left :
#             for idx, i in enumerate(left) :
#                 if target == i :
#                     return idx

#         if target in right :
#             for idx, j in enumerate(right):
#                 if target == j :
#                     return idx + len(left)

#         else :
#             return -1

class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums)-1 # 5

while left<=right :
middle = (left+right)//2  # 3
if nums[middle] == target :
return middle
elif nums[middle] < target :
left = middle + 1
elif nums[middle] > target :
right = middle - 1

return -1