LeetCode274-H指数

题目链接

英文链接:https://leetcode.com/problems/h-index/

中文链接:https://leetcode-cn.com/problems/h-index/

题目详述

给定一位研究者论文被引用次数的数组(被引用次数是非负整数)。编写一个方法,计算出研究者的 h 指数。

h 指数的定义: “h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (N 篇论文中)至多有 h 篇论文分别被引用了至少 h 次。(其余的 N - h 篇论文每篇被引用次数不多于 h 次。)”

示例:

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

说明: 如果 h 有多种可能的值,h 指数是其中最大的那个。

题目详解

  • h 的下界为 0,上界为 n,即 h 位于区间 [0, n]
  • 题意是找一个最大的 h,使得数组中有 h 个数大于等于 h。
  • 我们可以先对数组进行排序,然后从大到小枚举 h ,直到满足条件为止。
  • 时间复杂度为 O(nlogn),主要花在排序上。
1
2
3
4
5
6
7
8
9
10
11
12
13
public class LeetCode_00274 {

public int hIndex(int[] citations) {
Arrays.sort(citations);
int res = 0;
for (int i = 0; i < citations.length; ++i) {
if (citations[i] >= citations.length - i) {
return citations.length - i;
}
}
return 0;
}
}
  • 可以不用排序,可以用一个哈希表来存储出现次数,得到区间 [1, n] 的论文数目。
  • 仍旧是从大到小枚举 h,满足条件就直接返回。
  • 时间复杂度为 O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class LeetCode_00274 {

public int hIndex(int[] citations) {
int n = citations.length;
// 记录对应的引用次数
int[] cnt = new int[n + 1];
for (int c : citations) {
if (c <= n) { // <= n 直接记录
++cnt[c];
} else { // > n 记为 n
++cnt[n];
}
}
// 从大到小遍历,满足要求就直接返回
int sum = 0;
for (int i = n; i >= 0; --i) {
sum += cnt[i];
if (sum >= i) {
return i;
}
}
return 0;
}
}