Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
H-Index in C++
Suppose we have an array of citations (The citations are non-negative integers) of a researcher. We have to define a function to compute the researcher's h-index. According to the definition of h-index: "A scientist has index h if h of his/her 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 = [3,0,6,1,7], then the output will be 3, as it indicates that the researcher has five papers, they have got 3, 0, 6, 1, 7 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two paper with no more than 3 citations each, then the h-index is 3.
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
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int hIndex(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 = {3,0,6,1,7};
cout << (ob.hIndex(v));
}
Input
[3,0,6,1,7]
Output
3