题目

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.

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

方法一

思路

对于不知道h-index的请自行百度。

常识:如果N是citations的h-index,那么小于等于N的自然数都是citations的h-index。我们只需从1开始找,每次加1,直到找到第一个不是citations的h-index,这样我们就找到了citations的最大h-index。

代码

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int i = 0;
        int num = 0;
        do
        {
            i++;
            num = 0;
            for (vector<int>::iterator iter = citations.begin(); iter != citations.end(); ++iter)
            {
                if (*iter >= i)
                {
                    num++;
                }
            }
        }while (num >= i);
        
        return i - 1;
    }
};

方法二

思路

方法一的时间复杂度太高:O(N*M),其中N为citations的最大h-index,M为citations的元素个数。我们能否在线性时间内找到了?答案是显然的(显然?!呵呵,如果显然,我也不会网上搜索才知道)。

当我们将citations从大到小排序后,如果第1个数(即最大的数)大于1的话,1就是它的一个h-index(不一定是最大的);如果第2个数(即第二大的数)大于2的话,2也是它的一个h-index,因为第二大的数都大于2,那么第一大的数肯定也大于2,这样至少两个数大于2,那么2就是它的一个h-index……类推,只要第N个数(即第N大的数)大于N的话,N就是它的一个h-index。直到我们找到N+1不是它的h-index,那么N就是它的最大的h-index了。

代码

bool compareLargeToSmall(int i, int j)
{
    return i > j;
}

class Solution {
public:
    int hIndex(vector<int>& citations) {

        sort(citations.begin(), citations.end(), compareLargeToSmall); // 从大到小排序

        for (int i = 1; i <= citations.size(); ++i)
        {
            if (i > citations[i-1])
                return i - 1;
        }

        return citations.size();
    }
};

总结

其实,这么简单的一个排序处理,我应该要想到的。


chenhong2018
2 声望0 粉丝

« 上一篇
Ugly Number II