二分查找Python3实现
力扣 https://leetcode-cn.com/problems/binary-search/submissions/
题解
二分查找是需要背诵下来的算法,没撒难度,但是要是不会就很丢人。
class Solution:
def search(self, nums: List[int], target: int) -> int:
ans = -1
l=0
r=len(nums)-1
while l<=r:
p = (l+r)//2
if nums[p]<target:
l = p+1
elif nums[p]>target:
r = p-1
else:
ans = p
break
return ans