Given an array of integers nums
which is sorted in ascending order, and an integer target
, write a function to search target
in nums
. If target
exists, then return its index. Otherwise, return -1
.
You must write an algorithm with O(log n)
runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
1 <= nums.length <= 10^4
-10^4 < nums[i], target < 10^4
nums
are unique.nums
is sorted in ascending order.A brute force solution would involve iterating through the entire array and checking each element to see if it matches the target. This is a linear search.
def linear_search(nums, target):
for i in range(len(nums)):
if nums[i] == target:
return i
return -1
O(n), where n is the number of elements in the array.
O(1), as it only uses a constant amount of extra space.
Since the array is sorted, we can use binary search to find the target in O(log n) time.
left
to 0 and right
to len(nums) - 1
.left <= right
:
mid = (left + right) // 2
nums[mid] == target
, return mid
.nums[mid] < target
, the target must be in the right half, so update left = mid + 1
.nums[mid] > target
, the target must be in the left half, so update right = mid - 1
.def binary_search(nums, target):
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
O(log n), where n is the number of elements in the array. This is because binary search halves the search space in each iteration.
O(1), as it only uses a constant amount of extra space.
nums
is empty, the algorithm should return -1 immediately.