leetcode274 H指数 —— 排序后遍历/差分 c++/python

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

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

 

示例 1:

citations = [3,0,6,1,5]
5
3, 0, 6, 1, 5
3 
3
3
3

示例 2:

输入:citations = [1,3,1]
输出:1

 

提示:

  • n == citations.length
  • 1 <= n <= 5000
  • 0 <= citations[i] <= 1000

最容易理解的——排序后遍历

先对原数组进行排序,我们要找最大值的h就是要满足大于等于h的数大于等于h,所以排序之后我们可以知道大于每个数的数有多少,进行查找最大值即可

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
    int hIndex(vector<int>& citations) {
         
        sort(citations.begin(),citations.end());
        int n=citations.size();
        for(int i=0;i<n;i++) {
            if(citations[i]>=n-i) return n-i;
        }
        return 0;
 
    }
};

  

稍微优化——遍历改成二分搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
    int hIndex(vector<int>& citations) {
        size_t n = citations.size();
        sort(citations.begin(), citations.end());
        int low = 0, high = n - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (citations[mid] >= n - mid) high = mid - 1;
            else low = mid + 1;
        }
        return n - low;
    }
};

  

差分数组解法(计数排序)

差分数组讲解可参考【算法】排序算法之计数排序 - 知乎 (zhihu.com)

这里因为h<=n,所以大于n的数按n算就行,cnt数组大小n+1

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    int hIndex(vector<int>& citations) {
        //计数排序
        int n=citations.size();
        vector<int> counter(n+1) ;//因为h<=n,所以>n的值都存入counter[n]
        for(int i=0;i<n;i++) {
            if(citations[i]>=n) counter[n]++;
            else counter[citations[i]]++;
        }
 
        int cnt=0;//cnt记录大于i (即citations[某个值])的值个数
        for(int i=n;i>=0;i--) {//从大到小遍历
            cnt+=counter[i];
            if(cnt>=i) {
                //如果大于i的数个数大于i,那么h=i
                return i;
            }
        }
        return 0;
 
    }
};

  

python:

复制代码
class Solution:
    def hIndex(self, citations: List[int]) -> int:
        n=len(citations)
        counter=[0]*(n+1)
        for i in citations:
            if i >= n :
                counter[n]+=1
            else :
                counter[i]+=1
        
        cnt=0
        for i in range(n,-1,-1) :
            cnt+=counter[i]
            if cnt>=i:
                return i
        return 0
复制代码

 

posted @   夫琅禾费米线  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示