package com.harrison.Class01;
import java.util.Arrays;
public class Code06_BSNearRight {
public static int nearestIndex(int[] arr,int value) {
int l=0;
int r=arr.length-1;
int index=-1;
while(l<=r) {
int mid=l+((r-l)>>1);
if(arr[mid]<=value) {
index=mid;
l=mid+1;
}else {
r=mid-1;
}
}
return index;
}
//从右往左
public static int test(int[] arr,int value) {
for(int i=arr.length-1; i>=0; i--) {
if(arr[i]<=value) {
return i;
}
}
return -1;
}
public static int[] generateRandomArray(int maxSize,int maxValue) {
int[] arr=new int[(int)(Math.random()*(maxSize+1))];
for(int i=0; i<arr.length; i++) {
arr[i]=(int)(Math.random()*(maxValue+1))-(int)(Math.random()*maxValue);
}
return arr;
}
public static void printArray(int[] arr) {
if(arr==null) {
return ;
}
for(int i=0; i<arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String[] args) {
int testTimes=1000000;
int maxSize=100;
int maxValue=100;
boolean succeed=true;
for(int i=0; i<testTimes; i++) {
int value=(int)(Math.random()*(maxValue+1))-(int)(Math.random()*maxValue);
int[] arr=generateRandomArray(maxSize, maxValue);
Arrays.sort(arr);
if(nearestIndex(arr, value)!=test(arr, value)) {
printArray(arr);
System.out.println(value);
System.out.println(nearestIndex(arr, value));
System.out.println(test(arr, value));
succeed=false;
break;
}
}
System.out.println(succeed?"Nice":"Fucking fucked");
}
}
12-16
479
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-07
316
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-22
228
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)