Problem
For a given sorted array (ascending order) and a target number, find thefirst 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 2322^{32}232, can your code work properly?
题解
对于已排序升序(升序)数组,使用二分查找可满足复杂度要求,注意数组中可能有重复值,所以需要使用类似lower_bound中提到的方法。
Java
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) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = -1, end = nums.length;
int mid;
while (start + 1 < end) {
// avoid overflow when (end + start)
mid = start + (end - start) / 2;
if (nums[mid] < target) {
start = mid;
} else {
end = mid;
}
}
if (end == nums.length || nums[end] != target) {
return -1;
} else {
return end;
}
}
}
源码分析
复杂度分析
时间复杂度 O(logn)O(\log n)O(logn), 空间复杂度 (1)(1)(1).对于题中的 follow up, Java 中数组不允许使用 long 型,如果使用 long 型,那么数组大小可大 17GB 之巨!!几乎没法用。