274. H-Index和275. H-Index II

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

解法1(巧用定义)

class Solution {
public:
    int hIndex(vector<int>& citations) {
        if(citations.size()==0)
            return 0;
        sort(citations.begin(),citations.end(),cmp);
        for(int i=0;i<citations.size();i++){
            if(citations[i]<i+1)
                return i;
        }
        return citations.size();
    }  
    static bool cmp(int left,int right){return left>right;}
};

解法2(哈希表)

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int len=citations.size();
        vector<int> hash(len+1,0);
        int sum=0;
        if(len==0)
            return 0;
        for(auto i : citations){
            if(i>=len)
                hash[len]++;
            else
                hash[i]++;
        }
        
        for(int i=len;i>=0;i--){
            sum+=hash[i];
            if(sum>=i)
                return i;
        }
    }       
};
说是哈希表,其实是用一个数组来建立引用次数和这样的论文有几篇之间的关系。例如对于输入:3,0,6,1,5,使用一个数组:

0,1,2,3,4,5

1,1,0,1,0,2

第一行是数组下标,代表引用次数,第二行是论文数量。

然后倒着遍历,发现sum大于等于某个下标时就返回这个下标。

这个问题有一个follow-up:

如果数组已经排好序了,怎么高效计算H-index?答案是二分搜索。每次找到一个citations[mid],如果总长度是n,那么n-mid就是数组中不小于这个引用数的文章数,如果citations[mid]的值刚好等于这个文章数,正好符合H-index的定义,就是答案;如果citations[mid]的值大于剩下的文章数,这说明剩下的文章虽然引用数不小于citations[mid],但是没有那么多,只能在左半边找;反之,在右半边找。

一开始觉得citations[mid]是引用数,而n-mid是文章数,用这两个比较没有道理,后来联系H-index的定义才明白。。我真蠢。。

AC代码:

class Solution {  
public:  
    int hIndex(vector<int>& citations) {  
        int n=citations.size();
        int lo=0;
        int hi=n-1;  
        int mid;
        while(lo<=hi){
            mid=lo+(hi-lo)/2;
            if(citations[mid]>=n-mid)
                hi=mid-1;
            else
                lo=mid+1;
        }
        return n-lo;
    }       
};  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值