H-Index
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher’s h-index.
According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.
1 | Example 1: |
My solution
My idea is firstly sort the array first from the least to the largest.
1 | sort (citations.begin(), citations.end(), [](int & a, int & b){ |
Also, we create two variables, one is the hIndex
and the other is called count
. For the situation that the ith element is one of the h-index, which means i + citations[i]
is smaller than the length of the citations array, during the iteration, we update the maximum h-index.
For example, in the array 0,1,3,5,6
, 0 is one h-index; 1 is one h-index and it means the researcher has published at least 1 paper that has been cited at least 1 time; 3 is one h-index and it means the researcher has published at least 3 paper that has been cited at least 3 times, when we count i + citations[i]
, which is 2 + 3
, the result is equal to the length of the array. So we update the h-index to 3.
1 | In the loop: |
However, there exists some situation that not fit this method, for example, the array [0,0,4,4]
.
In this situation, our h-index is 0, however, the correct answer is 2 because the researcher has published 2 papers that have been cited at least 2 times. So I use the variable count
to handle this situation, once the result of i + citations[i]
is larger than the length of the array, we add one to the count.
1 | In the loop: |
After iteration, we return the larger one between the h-index
and the count
.
Full code
1 | class Solution { |