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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
解法1(巧用定义)
class Solution {
public:
int hIndex(vector<int>& citations) {
if(citations.size()==0)
return 0;
sort(citations.begin(),citations.end(),cmp);
for(int i=0;i<citations.size();i++){
if(citations[i]<i+1)
return i;
}
return citations.size();
}
static bool cmp(int left,int right){return left>right;}
};
解法2(哈希表)
class Solution {
public:
int hIndex(vector<int>& citations) {
int len=citations.size();
vector<int> hash(len+1,0);
int sum=0;
if(len==0)
return 0;
for(auto i : citations){
if(i>=len)
hash[len]++;
else
hash[i]++;
}
for(int i=len;i>=0;i--){
sum+=hash[i];
if(sum>=i)
return i;
}
}
};
0,1,2,3,4,5
1,1,0,1,0,2
第一行是数组下标,代表引用次数,第二行是论文数量。
然后倒着遍历,发现sum大于等于某个下标时就返回这个下标。
这个问题有一个follow-up:
如果数组已经排好序了,怎么高效计算H-index?答案是二分搜索。每次找到一个citations[mid],如果总长度是n,那么n-mid就是数组中不小于这个引用数的文章数,如果citations[mid]的值刚好等于这个文章数,正好符合H-index的定义,就是答案;如果citations[mid]的值大于剩下的文章数,这说明剩下的文章虽然引用数不小于citations[mid],但是没有那么多,只能在左半边找;反之,在右半边找。
一开始觉得citations[mid]是引用数,而n-mid是文章数,用这两个比较没有道理,后来联系H-index的定义才明白。。我真蠢。。
AC代码:
class Solution {
public:
int hIndex(vector<int>& citations) {
int n=citations.size();
int lo=0;
int hi=n-1;
int mid;
while(lo<=hi){
mid=lo+(hi-lo)/2;
if(citations[mid]>=n-mid)
hi=mid-1;
else
lo=mid+1;
}
return n-lo;
}
};