274. H-Index

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."

Example:

Input: citations = [3,0,6,1,5]
Output: 3 
Explanation: [3,0,6,1,5] 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, her h-index is 3.

Note: If there are several possible values for h, the maximum one is taken as the h-index.

solution: (reference: https://leetcode.com/problems/h-index/discuss/70768/Java-bucket-sort-O(n)-solution-with-detail-explanation)

用bucket sort,假设共有n 篇paper,那么我们维持n + 1 个bucket,bucket[i] 表示 citation 为 i 的paper数量,buckec[n] 表示 citation > n 的 paper数量。

然后,为找到最大的h-index,从右往左遍历bucket[i] 并累计paper 数目总量 count,如果count >= i,说明当前有 i (count = i) 篇 paper 的 citation 都大于 i ,那么 i 就是 greatest h-index. (剩下的 paper 每篇 citation 数肯定都小于 i)

time = O(n), space = O(n)

class Solution {
    public int hIndex(int[] citations) {
        int n = citations.length;
        int[] bucket = new int[n + 1];
        for(int citation : citations) {
            if(citation >= n) {
                bucket[n]++;
            } else {
                bucket[citation]++;
            }
        }
        
        int count = 0;
        for(int i = n; i >= 0; i--) {
            count += bucket[i];
            if(count >= i) {
                return i;
            }
        }
        return 0;
    }
}
原文地址:https://www.cnblogs.com/fatttcat/p/13515551.html