08在arr上,返回小于等于targetNum的最右的位置.zip
立即下载
资源介绍:
在arr上,返回小于等于targetNum的最右的位置。
如果没有则返回-1。
package class01;
import java.util.Arrays;
/**
* 在arr上,返回小于等于targetNum的最右的位置。
* 如果没有则返回-1。
*/
public class Code06_BSNearRight {
public static int nearestIndex(int[] arr, int targetNum) {
int L = 0;
int R = arr.length - 1;
int temp = -1;
while (L <= R) {
int mid = L + ((R - L) >> 1);
if (arr[mid] <= targetNum) {
temp = mid;
L = mid + 1;
} else {
R = mid - 1;
}
}
return temp;
}
public static int[] generateRandomArr(int maxSize, int maxValue) {
int[] arr = new int[(int) (Math.random() * maxSize)];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * maxValue) - (int) (Math.random() * maxValue);
}
return arr;
}
public static void printArr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}
System.out.println();
}
public static int test(int[] arr, int targetNum) {
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] <= targetNum) {
return i;
}
}
return -1;
}
public static int[] copyArr(int[] arr1) {
int[] arr2 = new int[arr1.length];
for (int i = 0; i < arr1.length; i++) {
arr2[i] = arr1[i];
}
return arr2;
}
public static void main(String[] args) {
int testTimes = 1000000;
int maxSize = 100;
int maxValue = 100;
boolean flag = true;
for (int i = 0; i < testTimes; i++) {
int[] arr1 = generateRandomArr(maxSize, maxValue);
int[] arr2 = copyArr(arr1);
Arrays.sort(arr2);
int targetNum = (int) (Math.random() * maxValue);
int resultNum = nearestIndex(arr2, targetNum);
int testNum = test(arr2, targetNum);
if (resultNum != testNum) {
System.out.println("oops!");
flag = isFlag(arr1, arr2, targetNum, resultNum, testNum);
}
}
int targetNum = (int) (Math.random() * maxValue);
int[] arr1 = generateRandomArr(maxSize, maxValue);
int[] arr2 = copyArr(arr1);
Arrays.sort(arr2);
int resultNum = nearestIndex(arr2, targetNum);
int testNum = test(arr2, targetNum);
boolean flag1 = isFlag(arr1, arr2, targetNum, resultNum, testNum);
System.out.println(flag ? "nice!" : "oops!");
}
private static boolean isFlag(int[] arr1, int[] arr2, int targetNum, int resultNum, int testNum) {
System.out.println("============================================================");
System.out.print("原来的数组:");
printArr(arr1);
System.out.print("升序后数组:");
printArr(arr2);
System.out.print("数组的索引:");
for (int i = 0; i < arr1.length; i++) {//索引
System.out.print(i + "\t");
}
System.out.println();
System.out.println("targetNum = " + targetNum);
System.out.println("resultNum = " + resultNum);
System.out.println("testNum = " + testNum);
System.out.println("============================================================");
return false;
}
}
资源文件列表:
08在arr上,返回小于等于targetNum的最右的位置。.zip 大约有1个文件
- 08在arr上,返回小于等于targetNum的最右的位置。.txt 3.44KB