给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1。
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.
样例
在数组 [1, 2, 3, 3, 4, 5, 10] 中二分查找3,返回2。
挑战
如果数组中的整数个数超过了2^32,你的算法是否会出错?
class Solution {
/**
* @param nums: The integer array.
* @param target: Target to find.
* @return: The first position of target. Position starts from 0.
*/
public int binarySearch(int[] nums, int target) {
int low = 0;
int high = nums.length;
while(low <= high) {
int mid = (high - low)/2 + low;
if(nums[mid] == target){
while(mid - 1 >= 0 && nums[mid - 1] == target){
mid--;
}
return mid;
}
else if(nums[mid] < target){
low = mid + 1;
}else {
high = mid - 1;
}
}
return -1;
}
}