H-Index
Problem
A researcher has papers with the given citation counts. The h-index is the largest h such that at least h papers have at least h citations each. Print h.
Constraints
- 1 <= n <= 10^5
Examples
Input
5 3 0 6 1 5
Output
3
Solutions
After sorting, the number of papers with at least a[i] citations is n - i. The first i that satisfies a[i] >= n - i gives the largest valid h.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The h-index.
* Approach: Sort and scan.
* Time : O(n log n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(int[] a) {
// Step 1: Sort the citation counts in ascending order.
java.util.Arrays.sort(a);
int n = a.length;
// Step 2: If the paper at index i is the weakest of the top (n - i) papers, then n - i papers have at least a[i] citations.
// The first index where a[i] >= n - i gives the answer n - i.
for (int i = 0; i < n; i++) {
if (a[i] >= n - i) {
return n - i;
}
}
return 0;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- How many papers have at least a[i] citations after sorting?