二分查找/排序
BM17 二分查找-I
1、请实现无重复数字的升序数组的二分查找
给定一个 元素升序的、无重复数字的整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标(下标从 0 开始),否则返回 -1
数据范围:0 ≤len(nums)≤2×10^5, 数组中任意值满足:∣val∣≤10^9
进阶:时间复杂度 O(logn) ,空间复杂度 O(1)
示例1
输入:[-1,0,3,4,6,10,13,14],13
返回值:6
说明:13 出现在nums中并且下标为 6
示例2
输入:[],3
返回值:-1
说明:nums为空,返回-1
示例3
输入:[-1,0,3,4,6,10,13,14],2
返回值:-1
说明:2 不存在nums中因此返回 -1
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param nums int整型一维数组
# @param target int整型
# @return int整型
#
class Solution:
def search(self , nums: List[int], target: int) -> int:
# write code here
# 方式一
result = self.func_one(nums, target)
# 方式二
result = self.func_two(nums, target)
# 方式三
result = self.func_three(nums, target, 0, len(nums)-1)
return result
def func_one(self , nums: List[int], target: int) -> int:
"""in 的方式"""
target_index = -1
if nums !=[] and target in nums:
target_index = nums.index(target)
return target_index
else:
return target_index
def func_two(self , nums: List[int], target: int) -> int:
"""迭代的方式"""
start = 0
end = len(nums) - 1
middle = 0
while start <= end:
middle = (start + end) // 2
if target == nums[middle]:
return middle
elif target < nums[middle]:
end = middle - 1
else:
start = middle + 1
return -1
def func_three(self , nums