274. H-Index

2017-05-04  本文已影响0人  RobotBerry

问题

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."

Note: If there are several possible values for h, the maximum one is taken as the h-index.

例子

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.

分析

题目有点绕,通俗点理解就是:有一个数组A,大小为n。现在要找一个数h,使得A有至少h个元素不小于h。

现假设数组为[3, 0, 6, 1, 5]。

要点

bucket sort. 大于n的元素被压缩到第n个bucket里。

时间复杂度

O(n)

空间复杂度

O(n)

代码

方法一

class Solution {
public:
    int hIndex(vector<int>& citations) {
        sort(citations.begin(), citations.end());
        for (int i = citations.size(); i >= 0; i--) {
            if (lower_bound(citations.begin(), citations.end(), i) - citations.begin() <= citations.size() - i)
                return i;
        }
        return 0;
    }
};

方法二

class Solution {
public:
    int hIndex(vector<int>& citations) {
        sort(citations.begin(), citations.end(), greater<int>());
        for (int i = citations.size(); i >= 1; i--) {
            if (citations[i - 1] >= i)
                return i;
        }
        return 0;
    }
};

方法三

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int n = citations.size(), count = 0;
        vector<int> bucket(n + 1, 0);
        for (int c : citations)
            bucket[min(c, n)]++;
        for (int i = n; i >= 0; i--) {
            count += bucket[i];
            if (count >= i) return i;
        }
        return 0;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读