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

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.

Analysis

h index:有h篇文章的citation至少h

  1. 用一个array count(长度比citation多1)来记录citation的数量。
  2. count[i] (i=0 to length-1)代表citation为i的paper数量。count[length]代表citation数值大于等于length的paper数量。
  3. 用total从后开始加,代表citation大于等于i的paper总数。如果paper总数大于i,代表有total篇paper的citation至少大于i,则这个i就是h index。如果都不满足,h index就是0.
citations = [3, 0, 6, 1, 5]
len = 5
c=3, count[3]++
c=0, count[0]++
c=6, count[5]++
c=1, count[1]++
c=5, count[5]++
count = [1,1,0,1,0,2]

有2篇大于等于5
有2篇大于等于4
有3篇大于等于3,返回3

Code

public int hIndex(int[] citations) {
    int len = citations.length;
    int[] count = new int[len+1];
    for(int c:citations){
        if(c>len){count[len]++;}
        else {count[c]++;}
    }
    int total = 0;
    for(int i=len; i>=0; i--){
        total+=count[i];
        if(total>=i) {return i;}
    }
    return 0;
}

Reference

Leetcode