二分查找
class Solution:
def search(self, nums: List[int], target: int) -> int:
'''
二分查找条件、有序且元素不重复 否则返回多个下标
'''
left, right = 0, len(nums) - 1
while left <= right:
middle = (left + right) // 2
if nums[middle] == target:
return middle
elif nums[middle] < target:
left = middle + 1
else:
right = middle - 1
else:
return -1
顺序查找
python列表的index方法找不到会报错
class Solution:
def search(self, nums: List[int], target: int) -> int:
try:
if nums.index(target) or nums.index(target)==0:
return nums.index(target)
except:
return -1
|