274 H-Index
Given an array of integers citations
where citations[i]
is the number of citations a researcher received for their i
-th paper, compute the researcher's h-index.
The h-index is defined as: A scientist has index h
if h
of their n
papers have at least h
citations each, and the other n − h
papers have no more than h
citations each.
Example 1:
Input: citations = [3,0,6,1,5]
Output: 3
Explanation: The researcher has 5 papers in total.
3 of them have at least 3 citations each and the remaining 2 have no more than 3 citations each.
Example 2:
Input: citations = [1,3,1]
Output: 1
Constraints:
n == citations.length
1 <= n <= 5000
0 <= citations[i] <= 1000
Approach (Sorting / Greedy)
- Sort
citations
. - Iterate through the sorted array from large to small number. For each paper at index
i
, check if citation is large or equal to count.
Time Complexity: O(n log n)
Space Complexity: O(1) if in-place sorting.
Solution:
Javascript Solution
var hIndex = function(citations) {
citations.sort((a, b) => b - a)
let h = 0
for(let i = 0; i < citations.length; i++) {
if(citations[i] >= i + 1) {
h = i + 1
} else {
break
}
}
return h
};
TypeScript Solution
function hIndex(citations: number[]): number {
citations.sort((a, b) => b - a)
let h = 0
for(let i = 0; i < citations.length; i++) {
if(citations[i] >= i + 1) {
h = i + 1
} else {
break
}
}
return h
};