H-Index II - Medium - L - Star

less than 1 minute read

Published:

Question

  • https://leetcode.com/problems/h-index-ii/

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 an 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

Approach

  • Binary Search

Solution

class Solution {
public:
    int hIndex(vector<int>& arr) {
        int n=arr.size();
        int l=0;
        int h=arr[n-1];
        int res=0;
        
        while(l<=h)
        {
            int mid=(l+h)/2;
            
            if(mid==0 || (n-mid>=0 && arr[n-mid]>=mid))
            {
                 l=mid+1;
                 res=mid;                              
            }
            else
                h=mid-1;
        }
        return res;
    }
};