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.
Solution:Bucket
思路:建一个bucket数组len=paper总数量,里面存的是citations数 对应的 paper数量,当citations数 > paper总数量,都放在length位置就ok,因为h-index最多只能paper总数量。
再从后遍历bucket并累积(paper数量累积),输出第一个大于index(citations数)的index值
Time Complexity: O(N) Space Complexity: O(N)
Solution Code:
class Solution {
public int hIndex(int[] citations) {
int len = citations.length;
if(len == 0) return 0;
// build a bucket where the index is the num of citations
// and the value is num of papers
int bucket[] = new int[len + 1];
for(int i = 0; i < len; i++) {
if(citations[i] > len) {
bucket[len]++;
}
else bucket[citations[i]]++;
}
//get result from bucket
int paper_num = 0;
for(int i = len; i >= 0; i--) {
paper_num += bucket[i];
if(paper_num >= i) return i;
}
return 0;
}
}