此内容尚不支持你的语言。
Search with closed interval on both ends [left, right].
[left, right]
1class Solution:2 def binary_search(self, nums: List[int], target: int) -> int:3 left, right = 0, len(nums) - 14 while left <= right:5 mid = left + (right - left) // 26 if nums[mid] == target:7 return mid8 elif nums[mid] < target:9 left = mid + 110 elif nums[mid] > target:11 right = mid - 112 return -1
1class Solution:2 def binary_search(self, nums: List[int], target: int) -> int:3 left, right = 0, len(nums) - 14 while left < right:5 mid = left + (right - left) // 26 if nums[mid] == target:7 return mid8 elif nums[mid] < target:9 left = mid + 110 elif nums[mid] > target:11 right = mid - 112 return left if nums[left] == target else -1
Search for the left bound of the target:
1class Solution:2 def search_left_bound(self, nums: List[int], target: int) -> int:3 left, right = 0, len(nums) - 14 while left <= right:5 mid = left + (right - left) // 26 if nums[mid] < target:7 left = mid + 18 elif nums[mid] > target:9 right = mid - 110 elif nums[mid] == target:11 right = mid - 112 if left >= len(nums) or nums[left] != target:13 return -114 return left
Search for the right bound of the target:
1class Solution:2 def search_right_bound(self, nums: List[int], target: int) -> int:3 left, right = 0, len(nums) - 14 while left <= right:5 mid = left + (right - left) // 26 if nums[mid] < target:7 left = mid + 18 elif nums[mid] > target:9 right = mid - 110 elif nums[mid] == target:11 left = mid + 112 if right < 0 or nums[right] != target:13 return -114 return right