- class Solution:
- def search(self, nums: List[int], target: int) -> int:
- l=0
- r=len(nums)-1 #1
- while l<=r: #2
- mid=int((l+r)/2)
- if nums[mid]>target:
- r=mid-1 #3
- elif nums[mid]<target:
- l=mid+1
- else:
- return mid
- return -1
非常基础的二分,但是解决了一直以来的边界处理问题:
根据统一的左右区间的开闭来判断边界,上述代码为左闭右闭,下面为左闭右开
- class Solution:
- def search(self, nums: List[int], target: int) -> int:
- l=0
- r=len(nums)
- while l<r:
- mid=int((l+r)/2)
- if nums[mid]>target:
- r=mid
- elif nums[mid]<target:
- l=mid+1
- else:
- return mid
- return -1