一个算法题
一个非降数组vec和一个数x,找到vec中最后一个x后面那个数的下标,找不到返回-1,二分查找的最优解法,怎么优化第二个while?
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
int[] arr = {1,2,3,4,4,5};
int res = help(arr,3);
System.out.print(res);
}
public static int help(int[] arr,int x) {
int len = arr.length;
if(len == 0)
return -1;
int l =0;
int r = len - 1;
while(l<=r) {
int mid = l + (r-l)/2;
if(arr[mid] == x) {
int flag = mid;
while(arr[flag] == x && flag < len)
flag++;
return flag;
}
if(arr[mid] < x) {
l = mid + 1;
} else
r = mid - 1;
}
return -1;
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
int[] arr = {1,2,3,4,4,5};
int res = help(arr,3);
System.out.print(res);
}
public static int help(int[] arr,int x) {
int len = arr.length;
if(len == 0)
return -1;
int l =0;
int r = len - 1;
while(l<=r) {
int mid = l + (r-l)/2;
if(arr[mid] == x) {
int flag = mid;
while(arr[flag] == x && flag < len)
flag++;
return flag;
}
if(arr[mid] < x) {
l = mid + 1;
} else
r = mid - 1;
}
return -1;
}
}