思路:要到达最大h指数,此时有a1篇引用大于等于h,a2篇引用等于h-1,且满足a1+min(a2, L)大于等于h,a1、a2可使用双指针分别获取,h则可使用二分法遍历减少耗时。
import java.util.*;
public class Main {
private static int N, L;
private static int[] a;
private static boolean check(int mid) {
int a1 = 0, a2 = 0;
for (int i = 1; i <= N; i++) {
if (a[i] >= mid) {
a1++;
}
else if (a[i] == mid - 1) {
a2++;
}
}
return a1 + Math.min(a2, L) >= mid;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
L = sc.nextInt();
a = new int[N + 2];
for (int i = 1; i <= N; i++) {
a[i] = sc.nextInt();
}
int left = 0, right = N;
while (left < right) {
int mid = left + right + 1 >> 1;
if (check(mid)) {
left = mid;
}
else {
right = mid - 1;
}
}
System.out.println(right);
}
}
标签:二分,int,3745,mid,a1,a2,static,指针
From: https://www.cnblogs.com/he0707/p/18095134/lanqiaobei04