给定一个排序的整数数组(升序)和一个要查找的整数target
,用O(logn)
的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1
。
在数组 [1, 2, 3, 3, 4, 5, 10]
中二分查找3
,返回2
。
python:
class Solution:
# @param nums: The integer array
# @param target: Target number to find
# @return the first position of target in nums, position start from 0
def binarySearch(self, nums, target):
# write your code here
low = 0
high = len(nums) - 1
while low <= high:
middle = (high + low) // 2
if nums[middle] < target:
low = middle + 1
elif nums[middle] > target:
high = middle - 1
else:
while nums[middle] == nums[middle - 1]:
middle -= 1
return middle
return -1
C++:
class Solution {
public:
/**
* @param nums: The integer array.
* @param target: Target number to find.
* @return: The first position of target. Position starts from 0.
*/
int binarySearch(vector<int> &array, int target) {
// write your code here
if (array.size() == 1)
{
if (array[0] == target)
return 0;
}
int start = 0;
int end = array.size();
int middle = end / 2;
while (array[middle] != target)
{
if (array[middle] > target)
{
end = middle - 1;
}
else
{
start = middle + 1;
}
middle = (start + end) / 2;
if (array[middle] < target && array[middle + 1] > target)
return -1;
}
while (array[middle] == array[middle - 1])
{
middle--;
}
return middle;
}
};