704. Binary Search
[Easy] “Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1."
Note: old solution, should review (TODO:
)
Python3:
class Solution:
def search(self, nums: List[int], target: int) -> int:
def binary_search(range_left, range_right):
mid = int((range_right - range_left) / 2) + range_left
if ((range_right - range_left) == 1) and (nums[mid] != target):
return -1
if target < nums[mid]:
res = binary_search(range_left, mid)
elif target > nums[mid]:
res = binary_search(mid, range_right)
elif target == nums[mid]:
res = mid
return res
return binary_search(0, len(nums))