704. Binary Search
## description
## 704. 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.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
1Input: nums = [-1,0,3,5,9,12], target = 9
2Output: 4
3Explanation: 9 exists in nums and its index is 4Example 2:
1Input: nums = [-1,0,3,5,9,12], target = 2
2Output: -1
3Explanation: 2 does not exist in nums so return -1- –1 <= nums.length <= 104
- –-104 < nums[i], target < 104
- –All the integers in nums are unique.
- –nums is sorted in ascending order.
Constraints:
## notes
### Intuition
In a sorted array, we can eliminate half the search space with each comparison. If the middle element is too small, the target must be in the right half; if too large, it's in the left half.
### Implementation
Maintain left and right pointers. While l ≤ r, calculate the midpoint. If nums[mid] equals the target, return mid. If it's less than the target, search the right half by setting l = mid + 1. If greater, search the left half by setting r = mid - 1. If the loop exits, the target doesn't exist—return -1.
### Edge-cases
The condition must be l ≤ r (not l < r) to handle the case where the target is the only remaining element when l == r.
- –Time: O(log n) — halve the search space each iteration
- –Space: O(1) — only tracking pointers
### Complexity
## solution
1from typing import List
2
3class Solution:
4 def search(self, nums: List[int], target: int) -> int:
5 l, r = 0, len(nums) - 1
6
7 while l <= r:
8 m = (l + r) // 2
9 if nums[m] == target:
10 return m
11 elif nums[m] < target:
12 l = m + 1
13 else:
14 r = m - 1
15
16 return -1
17
18
19
20if __name__ == "__main__":
21 # Include one-off tests here or debugging logic that can be run by running this file
22 # e.g. print(solution.two_sum([1, 2, 3, 4], 3))
23 solution = Solution()
24