274. H-Index

Medium

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

Example:

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

解答一:一开始是0篇至少0引用,然后1篇至少1引用,2篇至少2引用,...依此类推,不满足时终止。O(nlogn)

class Solution {
    public int hIndex(int[] citations) {
        if(citations==null || citations.length==0) return 0;
        Arrays.sort(citations);
        int res = 0;
        for(int i=citations.length-1;i>=0;i--){
            if(citations[i]>res)
                res++;
            else
                break;
        }
        return res;
    }
}

 解答二:采用桶排序,空间换时间,时间O(n),空间O(n),因为答案最大只可能取到len,为了节省空间,开辟len+1的辅助数组。遍历数组,如果数组元素a不小于n,bucket[n]加1;如果数组元素小于n,bucket[a]加一。接着定义一个total变量,从后往前累加bucket,如果total大于等于bucket下标i,则h=i。实际上total的含义的就是数组中不小于第i个元素的个数。
数组为[3, 0, 6, 1, 5],bucket初始化为[0, 0, 0, 0, 0],计数之后为[1, 1, 0, 1, 0, 2]。当i=5时,total=2, 2<5,不满足要求;i=4,total=2+0=2<4,不满足要求;i=3,total=2+1=3>=3,满足要求。因此h=3。

class Solution {
    public int hIndex(int[] citations) {
        int len = citations.length;
        int[] bucket = new int[len+1];6 5 5 5 5 存在取得最大长度的情况
        for(int i=0;i<citations.length;i++){
            if(citations[i]>=len)
                bucket[len]++;
            else
                bucket[citations[i]]++;
        }
        int sum = 0;
        for(int i=len;i>=0;i--){
            sum += bucket[i];
            if(sum>=i)
                return i;
        }
        return 0;
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值