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
Divide search space in half repeatedly. Apply binary search on sorted arrays or search space. Check middle element and adjust bounds based on comparison.
Implementation
def search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1Complexity Analysis
Time Complexity
O(log n)Space Complexity
O(1)Key Learning Points
Divide search space by 2Only works on sorted dataPrevent integer overflow with mid calculation
Related Problems to Practice
Binary SearchSearch in Rotated ArrayFind First/Last Position
Complexity
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