Program to find H-Index from a list of citations in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of citations of a researcher. We have to define a function to compute the researcher's h-index. As we know the h-index is a metric used to calculate the impact of a researcher's papers. Formally H-index can be defined as: "A researcher 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."

So, if the input is like citations = [5, 4, 1, 2, 6], then the output will be 3, as at least 3 papers have at least 3 citations each − 4, 5, 6.

To solve this, we will follow these steps −

  • n := size of the array, create one array called bucket of size n + 1
  • for i in range 0 to n – 1
    • x := c[i]
    • if x >= n, then increase bucket[n] by 1, otherwise increase bucket[x] by 1
  • cnt := 0
  • for i in range n down to 0:
    • increase cnt by bucket[i]
    • if cnt >= i, then return i
  • return – 1

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(vector<int>& c) {
      int n = c.size();
      vector <int> bucket(n + 1);
      for(int i = 0; i < n; i++){
         int x = c[i];
         if(x >= n){
            bucket[n]++;
         } else {
            bucket[x]++;
         }
      }
      int cnt = 0;
      for(int i = n; i >= 0; i--){
         cnt += bucket[i];
         if(cnt >= i)return i;
         } return -1;
      }
};
main(){
   Solution ob;
   vector<int> v = {5, 4, 1, 2, 6};
   cout << (ob.solve(v));
}

Input

[5, 4, 1, 2, 6]

Output

3
raja
Published on 19-Nov-2020 06:16:46
Advertisements