EasyLeetCode #704Binary Search
Binary Search
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.
Constraints
1 <= nums.length <= 10^4, -10^4 < nums[i], target < 10^4, All integers in nums are unique, nums is sorted in ascending order
Examples
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Solution
Approach
Classic binary search: repeatedly divide search space in half by comparing middle element with target.
def search(nums, target):
left, right = 0, 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 -1Complexity
Time:O(log n)
Space:O(1)
Hints
- 1.Array is sorted, use binary search
- 2.Compare middle element with target
- 3.Adjust left or right pointer accordingly
Asked at
Google