Header Ad

Leetcode H-Index II problem solution

In this Leetcode H-Index II 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 and citations is sorted in ascending order, 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. You must write an algorithm that runs in logarithmic time.

Leetcode H-Index II problem solution


Problem solution in Python.

class Solution:
    def hIndex(self, citations: List[int]) -> int:
        n = len(citations)
        if n == 0:
            return 0
        l = 0
        r = n
        while l<r:
            m = l + (r - l)//2
            if n - m <=citations[m]:
                r = m
            else:
                l = m + 1
        
        return n - l



Problem solution in Java.

public class Solution {
    public int hIndex(int[] citations) {
        if (citations.length == 0)
            return 0;
        else if (citations.length == 1) {
            if (citations[0] == 0)
                return 0;
            else
                return 1;
        }

        int n = citations.length;
        if (n <= citations[0]) // tricky optimization
            return n;

        int l = 1;
        int r = n;

        while (l < r) {
            int m = l + (r - l) / 2;

            if (n - m <= citations[m]) {
                r = m;
            } else {
                l = m + 1;
            }
        }

        return n - r;
    }
}


Problem solution in C++.

int hIndex(vector<int>& c,int ans=0) {
        for(int sz=c.size(),i=sz-1;i>=0;i--)  
            ans = max(ans,min(c[i],sz-i));
        return ans;
}


Problem solution in C.

int hIndex(int* citations, int citationsSize) {
    int lo = 0, hi = citationsSize, mid, index = 0;
    while (lo <= hi) {
        mid = lo + ((hi - lo) >> 1);
        if (citations[citationsSize - mid - 1] > mid) {
            lo = mid + 1;
            index = lo;
        } else {
            hi = mid - 1;
        }
    }
    return index;
}


Post a Comment

0 Comments