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 otherN − h papers have no more than h citations each."
For example, given citations = [3, 0, 6, 1, 5]
, which means the researcher has5
papers in total and each of them had received 3, 0, 6, 1, 5
citations respectively. Since the researcher has3
papers with at least 3
citations each and the remaining two withno 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.
public int hIndex(int[] citations) {
int length = citations.length;
if(length==0) return 0;
int[] array = new int[length+1];
for(int i=0;i<length;i++){
if(citations[i]>length){
array[length]+=1;
}
else{
array[citations[i]]+=1;
}
}
int t =0;
int result =0;
for(int i=length;i>=0;i--){
t = t+array[i];
if(t>=i) return i;
}
return 0;
}
总结:这道题自己把自己给绕晕了。其实不需要严格的排序,只需要统计。第一点,若citations值超过length,等价于length,这点要注意。第二点,要累加考虑。实际上使用了一个map。