H-Index II

Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.

Example:

Input: citations = [0,1,3,5,6]
Output: 3 

Approach

Java

public class HIndexII {
    public static void main(String[] args) {
        int[] citations = { 01356 };
        System.out.println(hIndex(citations));
    }

    static int hIndex(int[] citations) {
        int n = citations.length;
        int low = 0, high = n;
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (citations[mid] < n - mid)
                low = mid + 1;
            else
                high = mid;
        }
        return n - low;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int hIndex(vector<int>& citations
{
     int n=citations.size();
      int low=0,high=n;
      while(low<high)
      {
          int mid=low+(high-low)/2;
          if(citations[mid]<n-mid)
                 low=mid+1;
          else
              high=mid;
      }
        return n-low;
}

int main()
{
    vector<int>  citations ={0,1,3,5,6};
    cout<<hIndex(citations);
    return 0;
}


No comments:

Post a Comment