파이썬 알고리즘 인터뷰 65번(리트코드 704) Binary Search
https://leetcode.com/problems/binary-search/
class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
class Solution:
def search(self, nums: List[int], target: int) -> int:
def binary_search(left, right):
if left > right:
return -1
mid = left + (right - left) // 2
if nums[mid] < target:
return binary_search(mid + 1, right)
elif nums[mid] > target:
return binary_search(left, mid - 1)
else:
return mid
return binary_search(0, len(nums) - 1)
class Solution:
def search(self, nums: List[int], target: int) -> int:
index = bisect.bisect_left(nums, target)
if index < len(nums) and nums[index] == target:
return index
else:
return -1
# bisect 모듈에 대해 정리해보자
class Solution:
def search(self, nums: List[int], target: int) -> int:
try:
return nums.index(target)
except ValueError:
return -1
# try except 문 정리하자.
이진 탐색 모듈 bisect에 대해 자세히 정리한 글
try-except 구문에 대해 자세히 정리한 글