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
.
Example
If the array is [1, 2, 3, 3, 4, 5, 10]
, for given target 3
, return 2
.
Challenge
If the count of numbers is bigger than 2^32, can your code work properly?
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() == 0)
return -1;
int left = 0;
int right = array.size()-1;
while (left <= right)
{
int mid = left+(right-left)/2;
if (array[mid] == target)
{
if (mid > 0 && (array[mid-1] != target))
{
return mid;
}
else if (mid == 0)
{
return 0;
}
else
{
right = mid-1;
}
}
else if (array[mid] > target)
{
right = mid-1;
}
else
{
left = mid+1;
}
}
return -1;
}
};