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 thanh 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.
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.
Solution 1: Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int hIndex(vector<int>& citations) { | |
if(citations.size()==0) | |
return 0; | |
sort(citations.begin(), citations.end()); | |
reverse(citations.begin(), citations.end()); | |
int h=0; | |
for(int i=0; i<citations.size(); i++){ | |
int tmph; | |
tmph = i<citations[i]? i+1:citations[i]; | |
h=max(tmph, h); | |
} | |
return h; | |
} | |
}; |
The idea is lay in the fact that the h-index can not be larger than the length of the array. So, we can use a array with length n to store the number of papers with citation equal to the index of the array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
No comments:
Post a Comment