Problem Statement
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}232, can your code work properly?
使用二分搜索时应满足:数组必须已经排序,时间复杂度是O(logn)
/*
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}232, can your code work properly?
*/
public class Main {
public static void main(String[] args) {
int[] a = new int[] { 1, 2, 3, 3, 4, 5, 10 };
System.out.println(binarySearch(a, 3));
}
private static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
int mid = (left + right) / 2;
while (left < right) {
if (arr[mid] > target) {
right = mid;
} else if (arr[mid] < target) {
left = mid;
} else {
return mid;
}
mid = (left + right) / 2;
}
return -1;
}
}