H-Index

Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's 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."

Example:

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

Approach

Java

import java.util.Arrays;

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

    private static int hIndex(int[] citations) {
        Arrays.sort(citations);
        int n = citations.length;
        for (int i = 0; i < n; i++) {
            if (citations[i] >= n - i)
                return n - i;

        }
        return 0;
    }

}

C++

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

int hIndex(vector<int&citations)
{

    //sort the array in decresasing order
    sort(citations.begin(), citations.end(), greater<int>());
    for (int i = 0i < citations.size(); i++)
    {
        if (i >= citations[i])
        {
            return i;
        }
    }
    return citations.size();
}

int main()
{
    vector<intcitations = {30615};
    cout << hIndex(citations);
    return 0;
}


No comments:

Post a Comment