数组 二分查找
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例 2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
提示:
你可以假设 nums 中的所有元素是不重复的。
n 将在 [1, 10000]之间。
nums 的每个元素都将在 [-9999, 9999]之间。
来源:力扣(LeetCode)704
左闭右闭
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length = len(nums)
bottom = 0
high = length-1
index = -1
while(bottom<=high):
mid = (bottom + high) / 2
if nums[mid]==target:
index = mid
break
elif nums[mid]>target:
high=mid-1
else:
bottom=mid+1
return index
point
- 区间不变,左闭右闭 或 左闭右开
- 数组原始长度-1
使用二分法的前提
- 数组为有序数组
- 数组中无重复元素