Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
Hint:
- An easy approach is to sort the array first.
- What are the possible values of h-index?
- A faster approach is to use extra space.
1
我想的是最直接的方法,先排序,然后在从最大值开始判断。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Solution {
public int hIndex(int[] citations) {
if(citations == null) return 0;
quickSort(citations);
int n = citations.length;
for(int i = n; i >= 1; i--){
if(citations[n-i] >= i) return i;
}
return 0;
}
private void swap(int[] nums,int i, int j){
if(i == j) return;
if(nums[i] == nums[j]) return;
nums[i] ^= nums[j];
nums[j] ^= nums[i];
nums[i] ^= nums[j];
}
private boolean less(int[] a, int i, int j){
return a[i] < a[j];
}
public void quickSort(int[] nums){
if(nums == null || nums.length < 2) return;
quickSort(nums,0,nums.length - 1);
}
private void quickSort(int[] nums,int lo,int hi){
if(lo >= hi) return;
int j = partition(nums,lo,hi);
quickSort(nums,lo,j-1);
quickSort(nums,j+1,hi);
}
private int partition(int[] nums,int lo, int hi){
int i = lo;
int j = hi+1;
while(true){
while(less(nums,++i,lo)) if(i == hi) break;
while(less(nums,lo,--j)) if(j == lo) break;
if(i >= j) break;
swap(nums,i,j);
}
swap(nums,j,lo);
return j;
}
}
2 most votes
by pythonicjava
O(n)的方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public int hIndex(int[] citations) {
if(citations == null || citations.length == 0) return 0;
int n = citations.length;
int[] aux = new int[n+1];
for(int i = 0; i < n; i++){
if(citations[i] > n) aux[n]++;
else aux[citations[i]]++;
}
System.err.println(Arrays.toString(aux));
int sum = 0;
for(int i = n; i >= 1; i--){
sum += aux[i];
if(sum >= i) return i;
}
return 0;
}