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數(shù)組len=paper總數(shù)量,里面存的是citations數(shù) 對應(yīng)的 paper數(shù)量,當(dāng)citations數(shù) > paper總數(shù)量,都放在length位置就ok,因為h-index最多只能paper總數(shù)量。
再從后遍歷bucket并累積(paper數(shù)量累積),輸出第一個大于index(citations數(shù))的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;
}
}