274. H-Index
Problem
citations[i] is the citation count of a researcher's i-th paper. Return their h-index: the largest h such that at least h papers each have at least h citations.
Example: [3,0,6,1,5] → 3
Constraints: n ≤ 5000.
h ≤ n, so bucket citations into cnt[min(c, n)]. Walk h from n down, accumulating papers with ≥ h citations; the first h where that count ≥ h is the answer.
Complexity: O(n).
class Solution:
def hIndex(self, citations: List[int]) -> int:
n = len(citations)
cnt = [0] * (n + 1)
for c in citations:
cnt[min(c, n)] += 1
papers = 0
for h in range(n, -1, -1):
papers += cnt[h]
if papers >= h:
return h
return 0
assert Solution().hIndex([3, 0, 6, 1, 5]) == 3
assert Solution().hIndex([1, 3, 1]) == 1
class Solution {
public int hIndex(int[] citations) {
int n = citations.length;
int[] cnt = new int[n + 1];
for (int c : citations) cnt[Math.min(c, n)]++;
for (int h = n, papers = 0; h >= 0; h--) {
papers += cnt[h];
if (papers >= h) return h;
}
return 0;
}
}
func hIndex(citations []int) int {
n := len(citations)
cnt := make([]int, n+1) // cnt[c] = papers with c citations (capped at n)
for _, c := range citations {
cnt[min(c, n)]++
}
papers := 0
for h := n; h >= 0; h-- {
papers += cnt[h]
if papers >= h {
return h
}
}
return 0
}