题目描述
给你一个整数数组 citations ,其中 citations[i] 表示研究者的第 i 篇论文被引用的次数。计算并返回该研究者的 h 指数。
h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (n 篇论文中)总共有 h 篇论文分别被引用了至少 h 次。且其余的 n - h 篇论文每篇被引用次数 不超过 h 次。
例如:某人的 h 指数是 20,这表示他已发表的论文中,每篇被引用了至少 20 次的论文总共有 20 篇。
提示:如果 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
思路
方法一: 无脑暴力法
- 从1开始枚举到n看哪个数符合要求,维护一个maxh
方法二:降序排序
- 先降序排序,由于h指数的最大是n,直接从n开始判断。 又因为已经降序排了,若n满足条件,则前n个数一定大于n ,即直接判断第n个数是否大于n即可
- java降序很复杂,基本类型数组没有降序方法,要先转化为包装类型的数组。二者的转化方法如下:
基本类型数组->包装类型数组
Integer[] arrayInter = Arrays.stream(arrayInt).boxed().toArray(Integer[]::new);
包装类型数组->基本类型数组
int[] arrayInt2 = Arrays.stream(arrayInter2).mapToInt(Integer::valueOf).toArray();
方法三: 升序排序
1.不做降序操作,因为类型转换很耗时间和空间。 直接判断第n - h个数是否大于h
代码
方法一:
class Solution {
public int hIndex(int[] citations) {
int maxh = 0;
int n = citations.length;
for (int i = 1; i <= n; i ++){
int c = 0;
for (int j = 0; j < n; j ++){
if (citations[j] >= i){
c ++;
}
}
if (c >= i)
maxh = Math.max(maxh, i);
}
return maxh;
}
}
方法二:
class Solution {
public int hIndex(int[] citations) {
//将基本类型数组 转为 包装类型数组
Integer[] arrayInter = Arrays.stream(citations).boxed().toArray(Integer[]::new);
// 降序
Arrays.sort(arrayInter, Collections.reverseOrder());
//包装类型数组转回 基本类型 数组
int[] citation = Arrays.stream(arrayInter).mapToInt(Integer::valueOf).toArray();
int n = citation.length;
for (int h = n; h > 0; h --){
//直接判断第h个数 是否大于等于h
if (citation[h - 1] >= h) {
return h;
}
}
//上述循环没有找到, 则返回0
return 0;
}
}
方法三:
class Solution {
public int hIndex(int[] citations) {
Arrays.sort(citations);
int n = citations.length;
for (int h = n; h > 0; h -- ){
if (citations[n - h] >= h){
return h;
}
}
return 0;
}
}