描述
给定一个排序的整数数组(升序)和一个要查找的整数target
,用O(logn)
的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1
。
您在真实的面试中是否遇到过这个题?
是
样例
在数组 [1, 2, 3, 3, 4, 5, 10]
中二分查找3
,返回2
。
class Solution:
"" "
@param num s: The integer array.
@param targe t: Target to find .
@return: The first position of target. Position starts from 0 .
"" "
def binarySearch(self, nums, target):
# write your code here
left , right = 0 , len (nums)
while left + 1 <righ t:
mid= int (( left + right )/ 2 )
if nums[mid]<targe t:
left =mid
else :
right =mid
if nums[ left ]==targe t:
return left
elif nums[ right ]==targe t:
return right
return - 1
"" "
@param num s: The integer array.
@param targe t: Target to find .
@return: The first position of target. Position starts from 0 .
"" "
def binarySearch(self, nums, target):
# write your code here
left , right = 0 , len (nums)
while left + 1 <righ t:
mid= int (( left + right )/ 2 )
if nums[mid]<targe t:
left =mid
else :
right =mid
if nums[ left ]==targe t:
return left
elif nums[ right ]==targe t:
return right
return - 1