Binary Search¶
You are given an array of distinct integers nums, sorted in ascending order, and an integer target.
Implement a function to search for target within nums. If it exists, then return its index, otherwise, return -1.
Your solution must run in O ( l o g n ) O(logn) time.
Example 1:
Input: nums = [-1,0,2,4,6,8], target = 4
Output: 3 Example 2:
Input: nums = [-1,0,2,4,6,8], target = 3
Output: -1
In [4]:
def binary_search(nums,target):
l,r=0,len(nums)-1
while l<=r:
mid= (l+r)// 2
if target==nums[mid]:
return mid
elif target>nums[mid]:
l=mid+1
elif target<nums[mid]:
r=mid-1
In [5]:
print(binary_search([2,4,8,9,11,15],11))
4