题目链接:https://leetcode-cn.com/problems/binary-search/
题目:给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
这是普通的二分查找,思路比较简单,代码如下:
public int search(int[] nums, int target) {
if (nums == null) return -1;
int length = nums.length;
int left = 0;
int right = length-1;
while(left <= right){
int mid = (right - left )/2 + left;
if (nums[mid] == target) return mid;
else if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
下面是寻找左侧边界的二分搜索,例如数组[1,2,2,2,3],target为2,我们想输出第一个2的下标索引,输出1,这时我们要在常规二分查找中做些修改,当找到目标值后,我们不能马上输出,而是应该缩小右侧边界,最后考虑可能数组中的元素都比target小,考虑left越界情况。
public static int left_bound(int[] nums, int target) {
int left = 0,right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] == target) {
right = mid - 1;
}
}
if (left >= nums.length || nums[left] != target)
return -1;
return left;
}
例如数组[1,2,2,2,3],target为2,我们想输出最后一个2的下标索引,输出3。同理,右侧边界二分搜索也是类似,考虑可能数组中的元素都比target大,考虑right越界情况。
public static int right_bound(int[] nums, int target) {
int left = 0,right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] == target) {
left = mid + 1;
}
}
if (right < 0 || nums[right] != target)
return -1;
return right;
}
|