274.H指数

274.H指数

给你一个整数数组 citations ,其中 citations[i] 表示研究者的第 i 篇论文被引用的次数。计算并返回该研究者的 h 指数。
根据维基百科上 h 指数的定义:h 代表“高引用次数” ,一名科研人员的 h 指数 是指他(她)至少发表了 h 篇论文,并且 至少 有 h 篇论文被引用次数大于等于 h 。如果 h 有多种可能的值,h 指数 是其中最大的那个。

示例 1:
输入:citations = [3,0,6,1,5]
输出:3
解释:给定数组表示研究者总共有 5 篇论文,每篇论文相应的被引用了 3, 0, 6, 1, 5 次。
由于研究者有 3 篇论文每篇 至少 被引用了 3 次,其余两篇论文每篇被引用 不多于 3 次,所以她的 h 指数是 3。

示例 2:
输入:citations = [1,3,1]
输出:1

提示
n == citations.length
1 <= n <= 5000
0 <= citations[i] <= 1000
代码一
纯暴力,数据范围给的不大,直接从0到1010枚举即可,如果有新的h更新就行,其核心思想也就是用一个数组计数后,再从大到小进行累加,看当前的累加值是否大于我们当前给的i,如果是则返回i即可

代码一
class Solution {
public:
    int hIndex(vector<int>& citations) {
        int res=0;
        int les=citations.size();
        for(int i=1;i<=1010;i++){
            int sum=0;
            for(int j=0;j<les;j++){
                if(citations[j]>=i){
                    sum++;
                }
            }
            if(sum>=i) res=max(res,i); 
        }
        return res;
    }
};
代码二
class Solution {
public:
    int hIndex(vector<int>& citations) {
        int n = citations.size(), tot = 0;
        vector<int> counter(n + 1);
        for (int i = 0; i < n; i++) {
            if (citations[i] >= n) {
                counter[n]++;
            } else {
                counter[citations[i]]++;
            }
        }
        for (int i = n; i >= 0; i--) {
            tot += counter[i];
            if (tot >= i) {
                return i;
            }
        }
        return 0;
    }
};

代码二
优化上述代码,先对于citations数组排序,从大到小进行枚举,直到结束,就是所求的答案。

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

代码三
二分搜索,h的值在*0-citations.size()*之间,那么我们就是求得一个最大的h,那么可以用二分去枚举h,该复杂度为logn,此时我们再去扫描数组,时间复杂度为n,总的时间复杂度为nlogn。
通过本题,可以复习一下二分搜索的两种写法,写法不同,根据题意,采用正确的写法来使得二分搜索搜到正确的答案。

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int left=0,right=citations.size();
        int mid=0,cnt=0;
        while(left<right){
            // +1 防止死循环
            mid=(left+right+1)>>1;
            cnt=0;
            for(int i=0;i<citations.size();i++){
                if(citations[i]>=mid){
                    cnt++;
                }
            }
            if(cnt>=mid){
                // 答案在 [mid,right] 区间内
                left=mid;
            }else{
                // 答案在 [0,mid) 区间内
                right=mid-1;
            }
        }
        return left;
    }
};
  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值