Implement Binary Search From Scratch
Problem statement
Given an integer array sorted in nondecreasing order and a target, implement iterative binary search from scratch. Return the index of any occurrence of the target, or -1 when it is absent.
Function
binarySearch(nums: int[], target: int) → intExamples
Example 1
nums = [-4,-1,0,3,9]target = 3return = 3The target is at index 3.
Example 2
nums = [1,4,7,11]target = 5return = -1The target does not occur.
Constraints
0 <= nums.length <= 100000-10^9 <= nums[i], target <= 10^9numsis sorted in nondecreasing order.