For a given sorted array (ascending order) and a target
number, find the first index of this number in O(log n)
time complexity.
If the target number does not exist in the array, return -1
.
Yes
Example
If the array is [1, 2, 3, 3, 4, 5, 10]
, for given target 3
, return 2
.
二分查找
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
int len = array.size();
int i = recurse(array,target,0,len);
if (i != -1) {
while (array[i-1] == target) {
--i;
}
return i;
}
return -1;
}
int recurse(vector<int> &array, int target,int lo,int hi) {
if (lo == hi) {
return -1;
}
int mid = (lo + hi)>>1;
if (target > array[mid]) {
return recurse(array,target,mid+1,hi);
} else if (target < array[mid]) {
return recurse(array,target,lo,mid);
} else {
return mid;
}
}
};