Given a sorted array nums
, return the index of target
if it exists in the array, otherwise return -1
.
Iterative Binary Search
left
to 0
and right
to len(nums) - 1
as the bounds of the search range.left
is less than or equal to right
:
mid
index as (left + right) // 2
.nums[mid]
with target
:
mid
.nums[mid]
is greater than target
, adjust right
to mid - 1
to search in the left half.nums[mid]
is less than target
, adjust left
to mid + 1
to search in the right half.target
is not found after exiting the loop, return -1
.nums
. The search space is halved in each iteration.class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1