LeetCode274.H指数(Java)

题目

给你一个整数数组 citations ,其中 citations[i] 表示研究者的第 i 篇论文被引用的次数。计算并返回该研究者的 h 指数

根据维基百科上 h 指数的定义h 代表“高引用次数” ,一名科研人员的 h 指数 是指他(她)至少发表了 h 篇论文,并且 至少 有 h 篇论文被引用次数大于等于 h 。如果 h 有多种可能的值,h 指数 是其中最大的那个。

跳转链接:LeetCode274

解析

本题给你一个数组,要求求出最大的 h 值,使得数组中有至少 h 个值大于等于 h 的数。

解法一

首先进行升序排序,我们假设 h 为数组中的最大元素,然后慢慢递减。第一次循环时,会得到大于 h 的元素的个数 count,由于 h 是递减的因此 count 只会持续增加。当 count 的数量大于等于 h 时,会得到最大的 h ,这时直接跳出循环或者return。

public class Solution {

    public static int hIndex(int[] citations) {
        Arrays.sort(citations);
        int n = citations.length, h = citations[n - 1], count = 0;
        while(h > 0){
            /*
            由于citations是升序,
            当citations[n - 1 - count]小于h时代表已经不存在大于h的数
            */
            while(count < n && citations[n - 1 - count] >= h) {
                //如果大于等于h的元素的个数count大于等于h则代表得到了最大的h
                if(count++ >= h) {
                    break;
                }
            }
            //跳出循环
            if(count >= h) {
                break;
            }
            h--;
        }
        return h;
    }

}

解法二

首先进行升序排序,从数组的最后一个元素向前遍历,h从0开始慢慢增加,如果 citatoins[index] > h 则代表存在 h 个值大于 h 的数,当 citatoins[index] <= h 时则代表这个数不可能大于当前的 h 。因此 h 达到了最大值,继续遍历不可能会出现更大的 h 了。

public class Solution {

    public static int hIndex(int[] citations) {
        Arrays.sort(citations);
        int h = 0, index = citations.length - 1;
        /*
        从最后一个数(也就是最大的数)开始向前遍历,
        如果该数的值大于h,则h加一
        * */
        while(index >= 0 && citations[index] > h){
            h++;
            index--;
        }
        return h;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值