LeetCode 面试经典150题 [11/150 H指数]


avatar
GuoYulong 2024-06-18 141

题目描述

给你一个整数数组 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

个人C++解答

这次的解答写的很拉胯,想到了用排序,但是忘记了C++排序有库(习惯性的按照C语言的思路来写了),就没排序硬写了,主要就是将 citations 中的每个数对应的 H 计算出来,然后最后return最大的H,实际上官方更巧妙。

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int return_num = 0, count = 0,  temp=0;
        for (int front = 0; front < citations.size(); front++) {
            for (int rear = 0; rear < citations.size(); rear++) {
                if (citations[rear] >= citations[front]) count++;
            }
            temp = citations[front] < citations.size() ? citations[front] : citations.size();
            temp = temp < count ? temp : count;
            count = 0;
            if (temp > return_num) return_num = temp;
        }
        return return_num;
    }
};

官方题解

方法一:排序
首先我们可以将初始的 H指数 h 设为 0,然后将引用次数排序,并且对排序后的数组从大到小遍历。

根据 H 指数的定义,如果当前 H 指数为 hhh 并且在遍历过程中找到当前值 citations[i]>h,则说明我们找到了一篇被引用了至少 h+1 次的论文,所以将现有的 h 值加 1。继续遍历直到 h 无法继续增大。最后返回 h 作为最终答案。
作者:力扣官方题解
链接:https://leetcode.cn/problems/h-index/solutions/869042/h-zhi-shu-by-leetcode-solution-fnhl/

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;
    }
};

方法二:计数排序
根据上述解法我们发现,最终的时间复杂度与排序算法的时间复杂度有关,所以我们可以使用计数排序算法,新建并维护一个数组 counter 用来记录当前引用次数的论文有几篇。

根据定义,我们可以发现 H 指数不可能大于总的论文发表数,所以对于引用次数超过论文发表数的情况,我们可以将其按照总的论文发表数来计算即可。这样我们可以限制参与排序的数的大小为 [0,n](其中 n 为总的论文发表数),使得计数排序的时间复杂度降低到 O(n)。

最后我们可以从后向前遍历数组 counter,对于每个 0≤i≤n0,在数组 counter 中得到大于或等于当前引用次数 i的总论文数。当我们找到一个 H指数时跳出循环,并返回结果。
作者:力扣官方题解
链接:https://leetcode.cn/problems/h-index/solutions/869042/h-zhi-shu-by-leetcode-solution-fnhl/

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;
    }
};

相关阅读

注意!!!

新增会员中心页面,方便管理个人账户,充值功能暂不开启,请勿为本网站进行任何充值活动!!!

通知!!!

① 过年好!!!拖更几个月了已经,年后继续更新!!