Medium
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 hcitations each."
Example:
Input: citations = [3,0,6,1,5]
Output: 3
解答一:一开始是0篇至少0引用,然后1篇至少1引用,2篇至少2引用,...依此类推,不满足时终止。O(nlogn)
class Solution {
public int hIndex(int[] citations) {
if(citations==null || citations.length==0) return 0;
Arrays.sort(citations);
int res = 0;
for(int i=citations.length-1;i>=0;i--){
if(citations[i]>res)
res++;
else
break;
}
return res;
}
}
解答二:采用桶排序,空间换时间,时间O(n),空间O(n),因为答案最大只可能取到len,为了节省空间,开辟len+1的辅助数组。遍历数组,如果数组元素a不小于n,bucket[n]加1;如果数组元素小于n,bucket[a]加一。接着定义一个total变量,从后往前累加bucket,如果total大于等于bucket下标i,则h=i。实际上total的含义的就是数组中不小于第i个元素的个数。
数组为[3, 0, 6, 1, 5],bucket初始化为[0, 0, 0, 0, 0],计数之后为[1, 1, 0, 1, 0, 2]。当i=5时,total=2, 2<5,不满足要求;i=4,total=2+0=2<4,不满足要求;i=3,total=2+1=3>=3,满足要求。因此h=3。
class Solution {
public int hIndex(int[] citations) {
int len = citations.length;
int[] bucket = new int[len+1];6 5 5 5 5 存在取得最大长度的情况
for(int i=0;i<citations.length;i++){
if(citations[i]>=len)
bucket[len]++;
else
bucket[citations[i]]++;
}
int sum = 0;
for(int i=len;i>=0;i--){
sum += bucket[i];
if(sum>=i)
return i;
}
return 0;
}
}