二分查找
二分查找的三种情况
ps:二分查找的前提是数组是有序数组
- 数组无重复元素,查找升序数组nums[]中是否包含target,包含则返回给定目标值所在位置的下标,不包含则返回-1;
- 数组可能存在重复元素,查找升序数组nums[]中是否包含target,包含则返回给定目标值在数组中开始位置的下标,否则返回-1;
- 数组可能存在重复元素,查找升序数组nums[]中是否包含target,包含则返回给定目标值在数组中结束位置的下标,否则返回-1;
数组无重复元素,查找升序数组nums[]中是否包含target,包含则返回给定目标值所在位置的下标,不包含则返回-1;
nums = [2, 3, 4, 8, 9],target = 8,结果应当返回3;target = 7,结果应当返回-1;
public int binarySearchIndex(int[] nums, int target) {
int right = nums.length - 1, left = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] == target){
return mid;
}
}
return -1;
}
数组可能存在重复元素,查找升序数组nums[]中是否包含target,包含则返回给定目标值在数组中开始位置的下标,否则返回-1;
nums = [1, 2, 2, 5, 5, 8, 9, 9, 9, 9],target = 9,结果应当返回6;target = 7,结果应当返回-1;
//查询左边边界
public int BinarySearchLeftIndex(int[] nums, int target) {
int right = nums.length - 1, left = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
}
}
if (left >= nums.length || nums[left] != target) return -1;
return left;
}
数组可能存在重复元素,查找升序数组nums[]中是否包含target,包含则返回给定目标值在数组中结束位置的下标,否则返回-1;
nums = [1, 2, 2, 5, 5, 8, 9, 9, 9, 9],target = 9,结果应当返回9;target = 7,结果应当返回-1;
//查询右边边界
public int BinarySearchRightIndex(int[] nums, int target) {
int right = nums.length - 1, left = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
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;
}