二分查找模版
package com.zhang.reflection.面试.算法模版.二分查找模版;
public class 二分查找模版 {
/**
* 查找满足 x ≥ target 的下界的第一个元素下标,如果不存在返回数组的长度
* 同理找上界,找下界,找特定值第一次出现的位置都可以,前提是数组有序或者部分有序
*/
//找下界
public static int LowerBound(int[] nums, int target) {
int left=0;
int right=nums.length-1;
//跳出条件
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>=target){
right=mid-1;
}else{
left=mid+1;
}
}
return left;
}
//找上界
public static int UpperBound(int[] nums, int target) {
int left=0;
int right=nums.length-1;
//跳出条件
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>target){
right=mid-1;
}else{
left=mid+1;
}
}
return left-1;
}
//找该值第一次出现的位置
public static int FirstBound(int[] nums, int target) {
int left=0;
int right=nums.length-1;
//跳出条件
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>=target){
right=mid-1;
}else{
left=mid+1;
}
}
if(left>=nums.length||nums[left]!=target){
return -1;
}
return left;
}
//查找指定值最后一次出现的位置
//找上界
public static int LastBound(int[] nums, int target) {
int left=0;
int right=nums.length-1;
//跳出条件
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>target){
right=mid-1;
}else{
left=mid+1;
}
}
if(left-1>=nums.length||nums[left-1]!=target){
return -1;
}
return left-1;
}
public static void main(String[] args) {
int[] nums={5,7,7,8,8,10};
int target=8;
System.out.println(LastBound(nums,target));
System.out.println(UpperBound(nums,target));
System.out.println(FirstBound(nums,target));
System.out.println(LastBound(nums,target));
}
}