给定一个 n
个元素有序的(升序)整型数组 nums
和一个目标值 target
,写一个函数搜索 nums
中的 target
,如果目标值存在返回下标,否则返回 -1
。
示例 1:
输入: nums= [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums中并且下标为 4
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
else:
return -1
执行用时: 64 ms, 在Binary Search的Python3提交中击败了77.94% 的用户
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l=0
h=len(nums)-1
while l<=h:
mid=(l+h)//2
if nums[mid]==target:
return mid
if nums[mid]>target:
h=mid-1
else:
l=mid+1
return -1
执行用时: 64 ms, 在Binary Search的Python3提交中击败了77.94% 的用户