In this Leetcode H-Index problem solution, we have given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index.

According to the definition of h-index on Wikipedia: A scientist has an 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.

If there are several possible values for h, the maximum one is taken as the h-index.

Leetcode H-Index problem solution


Problem solution in Python.

class Solution:
    def hIndex(self, citations: List[int]) -> int:
        if not citations:
            return 0
        citations.sort()
        h = len(citations)
        if citations[0] >= h:
            return h
        else:
            for i in range(1, len(citations)+1):
                if h <= citations[i-1]:
                    return h
                h -= 1
        return h



Problem solution in Java.

public int hIndex(int[] citations) {
        Arrays.sort(citations);
        int h = 0;
        for(int i = citations.length - 1; i >= 0; i--){
            if(citations[i] < h + 1) break;
            h += 1;
        }
        return h;
    }


Problem solution in C++.

class Solution {
public:
int hIndex(vector<int>& citations) {
    int n=citations.size();
    if(n==0)
        return 0;
        
    sort(citations.begin(),citations.end());
    int res=0;
    for(int i=0;i<n;i++){
        if(citations[i]>=n-i)
            res=max(res,n-i);
    }
    return res;
}
};


Problem solution in C.

int partition(int a[], int p, int r) {
    int temp = 0;
    int i = p;
    int j = p;
    int pivot = a[r];
    
    for (j = p; j < r; j++) {
        if (a[j] > pivot) {
            temp = a[j];
            a[j] = a[i];
            a[i] = temp;
            i++;
        }
    }
    
    temp = a[r];
    a[r] = a[i];
    a[i] = temp;
    
    return i;
}

void quickSort(int a[], int p, int r) {
    if (p >= r) {
        return;
    }
    
    int q = partition(a, p, r);
    quickSort(a, p, q - 1);
    quickSort(a, q + 1, r);
}

int hIndex(int* citations, int citationsSize) {
    quickSort(citations, 0, citationsSize - 1);
    
    int i = 0;
    int ret = 0;
    for (i = 0; i < citationsSize; i++) {
        if (citations[i] >= i + 1) {
            ret = i + 1 > ret ? i + 1 : ret;
        }
    }
    
    return ret;
}