Binary Search 二分查找
给定有序数组,查找第一个目标数字。
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.
ExampleIf the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.
Solution:
非递归:
public int binarySearch(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
int mid;
while (start + 1 < end) {
mid = (start + ((end - start) >> 1));
if (target <= nums[mid]) {
end = mid;
} else {
start = mid;
}
}
if (nums[start] == target) {
return start;
} else if (nums[end] == target) {
return end;
} else {
return -1;
}
}
递归:
public int binarySearch(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
return bs(nums, 0, nums.length - 1, target);
}
private int bs(int[] nums, int target, int start, int end) {
if (start + 1 < end) {
int mid = start + ((end - start) >> 1);
if (target <= nums[mid]) {
return bs(nums, target, start, mid);
} else {
return bs(nums, target, mid, end);
}
} else {
if (nums[start] == target) {
return start;
} else if (nums[end] == target) {
return end;
} else {
return -1;
}
}
}
思路:
1. base case: start, mid, end (start + 1 = mid, mid + 1 = end). 其中一个为target则命中。 跳出循环时为start + 1 == end, 即start与end相邻。
2. Find first: 当mid命中时,end = mid, 看前面的有没有,先判断start。
3. Find last: 当mid命中时,start = mid,看后面的有没有,先判断end。