找>=某个数最左的位置
//有序数组最左匹配
public class mostleft {
public static void main(String[] args) {
int[] arr = {0,0,0,1,1,2,2,2,2,2,2,3,3,3,3,3,4,4,4};
System.out.println(left_match(arr,2));//5
}
//
public static int left_match(int[] arr,int num){
if(arr==null || arr.length==0){
return -1;
}
int l=0;
int r=arr.length-1;
int ans=-1;
while (l<=r){等于r是要把所有的数都测试完
int mid=(l+r)/2;
if(arr[mid]>=num){
/* 一直二分到最后一个数如果最后一个数是>=目标值的,此时就是最左的位置如果最后一个数不是>=目标值就说明上一次记录的index是最左的位置*/
ans=mid;
r=mid-1;
}else {
l=mid+1;
}
}
return ans;
}
}
找<=某个数最右的位置
public class mostright {
public static void main(String[] args) {
int[] arr = {0,0,0,1,1,2,2,2,2,2,2,3,3,3,3,3,4,4,4};
System.out.println(right_match(arr,2));//10
System.out.println(right_match(arr,10));//18
}
//
public static int right_match(int[] arr,int num){
if(arr == null || arr.length==0){
return -1;
}
int l=0;
int r=arr.length-1;
int ans=-1;
while (l<=r){
int mid=(l+r)/2;
if(arr[mid]<=num){
ans=mid;
l=mid+1;
}
else {
r=mid-1;
}
}
return ans;
}
}