Sponsored
Sponsored
Given the array is sorted, we can efficiently search for the h-index using binary search, aiming for logarithmic time complexity. The idea is to use the binary search to find the maximum h such that citations[h] ≥ h.
Time Complexity: O(log n).
Space Complexity: O(1).
1function hIndex(citations) {
2 let n = citations.length;
3 let left = 0, right = n - 1;
4 while (left <= right) {
5 let mid = Math.floor((left + right) / 2);
6 if (citations[mid] === n - mid) {
7 return n - mid;
8 } else if (citations[mid] < n - mid) {
9 left = mid + 1;
10 } else {
11 right = mid - 1;
12 }
13 }
14 return n - left;
15}
16
17let citations = [0, 1, 3, 5, 6];
18console.log(hIndex(citations)); // Output: 3
In JavaScript, the function hIndex
uses binary search by evaluating the middle of citations
to find the number of papers sufficiently cited. This solution offers logarithmic efficiency and leverages JavaScript's dynamic typing.
In this linear scan approach, we traverse the sorted citations list from beginning to end. The goal is to determine the maximum valid h-index by checking citations against their corresponding paper count.
Time Complexity: O(n).
Space Complexity: O(1).
1#include
This C implementation uses a simple loop to check each citation's sufficiency against its position in the list, returning the calculated h-index when the condition is satisfied.