Friday, April 22, 2016

LeetCode Q274: H-Index

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:
  1. An easy approach is to sort the array first.
  2. What are the possible values of h-index?
  3. A faster approach is to use extra space.
Solution 1: Sort

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;
}
};
view raw Q274-1.cpp hosted with ❤ by GitHub
Solution 2: Hash table
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.

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;
}
view raw Q274-2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment