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.
先放一个错误的解答:
class Solution {
public:
int hIndex(vector<int>& citations) {
//首先对citations排序,对于每一个位置i,我们去检查:
//1)它前面是不是有N-citations[i]个数小于等于它
//2)它后面(包括它自己)是不是有citations[i]个数大于等于它
//例如样例中的[3,0,6,1,5]排序后是[0,1,3,5,6]
//对于0,前面没有5个数小于它
//对于1,前面没有4个数小于它
//对于3,前面有2个数小于它,后面(包括它自己)有3个数大于等于它,3可能是答案
//...
//最后返回答案中最大的(第二次排序)
int i,j,k;
int size=citations.size();
int other,cnt_less,cnt_ge;
vector<int> possible_h;
if(citations.empty())
return 0;
sort(citations.begin(),citations.end());
for(i=0;i<size;i++){
cnt_less=cnt_ge=0;
other=size-citations[i];
for(j=i-1;j>=0;j--){
if(citations[j]<=citations[i])
cnt_less++;
}
for(k=i;k<size;k++){
if(citations[k]>=citations[i])
cnt_ge++;
}
if(cnt_less==other&&cnt_ge==citations[i])
possible_h.push_back(citations[i]);
else
possible_h.push_back(0);
}
sort(possible_h.begin(),possible_h.end());
return possible_h[possible_h.size()-1];
}
};
但是这样过不了像[11,13]这样的边界条件。。。想来想去都不知道怎么改了quq。。。。
这是人家的解答:
class Solution {
public:
int hIndex(vector<int>& citations) {
sort(citations.begin(),citations.end());
int len=citations.size();
for(int i=0;i<len;i++){
if(citations[i]>=len-i)
return len-i;
}
return 0;
}
};
还有一个hash表:
int hIndex(vector<int>& citations) {
if(citations.empty())
return 0;
int n = citations.size();
vector<int> hash(n + 1, 0);
for(int i = 0; i < n; ++i){
if(citations[i] >= n)
hash[n]++;
else
hash[citations[i]]++;
}
int paper = 0;
for(int i = n; i >= 0; --i){
paper += hash[i];
if(paper >= i)
return i;
}
}
思路是:答案只可能在0——N之间(N是数组元素个数)。把0——N看成引用数,那么就可以建立起引用数和被引文章数量的对应关系。比如样例:3,0,6,1,5。
引用数0 1 2 3 4 5对应的文章数是1 0 1 0 2。
这样只要从后往前加这些文章数,当文章数大于等于引用数就返回。