LeetCode Solutions
274. H-Index
Time: $O(n)$ Space: $O(n)$
class Solution {
public:
int hIndex(vector<int>& citations) {
const int n = citations.size();
int accumulate = 0;
vector<int> count(n + 1);
for (const int citation : citations)
++count[min(citation, n)];
// To find the largeset h-index, loop from back to front
// I is the candidate h-index
for (int i = n; i >= 0; --i) {
accumulate += count[i];
if (accumulate >= i)
return i;
}
throw;
}
};
class Solution {
public int hIndex(int[] citations) {
final int n = citations.length;
int accumulate = 0;
int[] count = new int[n + 1];
for (final int citation : citations)
++count[Math.min(citation, n)];
// To find the largeset h-index, loop from back to front
// I is the candidate h-index
for (int i = n; i >= 0; --i) {
accumulate += count[i];
if (accumulate >= i)
return i;
}
throw new IllegalArgumentException();
}
}
class Solution:
def hIndex(self, citations: List[int]) -> int:
n = len(citations)
accumulate = 0
count = [0] * (n + 1)
for citation in citations:
count[min(citation, n)] += 1
# To find the largeset h-index, loop from back to front
# I is the candidate h-index
for i, c in reversed(list(enumerate(count))):
accumulate += c
if accumulate >= i:
return i