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:
Java Solution
class Solution {
public int hIndex(int[] citations) {
Arrays.sort(citations);
var h = 0;
for(var i = citations.length - 1; i >= 0; i--) {
if(citations[i] >= citations.length - i) {
h = citations.length - i;
} else {
break;
}
}
return h;
}
}
Kotlin Solution
class Solution {
fun hIndex(citations: IntArray): Int {
citations.sortDescending()
var h = 0
for(i in citations.indices) {
if(citations[i] >= i + 1) {
h = i + 1
} else {
break
}
}
return h
}
}
Golang Solution
func hIndex(citations []int) int {
sort.Sort(sort.Reverse(sort.IntSlice(citations)))
h := 0
for i := 0; i< len(citations); i++ {
if citations[i] >= i + 1 {
h = i + 1
} else {
break
}
}
return h
}