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.

According to the definition of h-index on Wikipedia: "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."

For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3.

class Solution {
public:
    int hIndex(vector<int>& citations) {
        sort(citations.begin(), citations.end(), greater<int>());

        for(size_t i = 0; i < citations.size(); ++i){
            //遍历到i的时候,此时已经有i个元素了,如果此时i > citations[i],就说明前i个元素的citation均等于大于citations[i],
            if(i >= citations[i])
                return i;
        }
        return citations.size();
    }
};

我们发现h-index的范围在(0, n)之间 额外的空间O(n),时间复杂度为O(n)

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int n = citations.size();

        vector<int> count(n + 1, 0);

        for(auto &m:citations){
            //这个表示大于等于n的引用归到引用为n下面
            if(m >= n)
                count[n]++;
            else
                count[m]++;
        }

        int cita = 0;
        for(int i = n; i >= 0; i--){
            cita += count[i];
            if(cita >= i)
                return i;
        }
        return 0;
    }
};

results matching ""

    No results matching ""