题目
给你一个整数数组 citations ,其中 citations[i] 表示研究者的第 i 篇论文被引用的次数。计算并返回该研究者的 h 指数。
根据维基百科上 h 指数的定义:h 代表“高引用次数” ,一名科研人员的 h 指数 是指他(她)至少发表了 h 篇论文,并且 至少 有 h 篇论文被引用次数大于等于 h 。如果 h 有多种可能的值,h 指数 是其中最大的那个。
跳转链接:LeetCode274
解析
本题给你一个数组,要求求出最大的 h 值,使得数组中有至少 h 个值大于等于 h 的数。
解法一
首先进行升序排序,我们假设 h 为数组中的最大元素,然后慢慢递减。第一次循环时,会得到大于 h 的元素的个数 count,由于 h 是递减的因此 count 只会持续增加。当 count 的数量大于等于 h 时,会得到最大的 h ,这时直接跳出循环或者return。
public class Solution {
public static int hIndex(int[] citations) {
Arrays.sort(citations);
int n = citations.length, h = citations[n - 1], count = 0;
while(h > 0){
/*
由于citations是升序,
当citations[n - 1 - count]小于h时代表已经不存在大于h的数
*/
while(count < n && citations[n - 1 - count] >= h) {
//如果大于等于h的元素的个数count大于等于h则代表得到了最大的h
if(count++ >= h) {
break;
}
}
//跳出循环
if(count >= h) {
break;
}
h--;
}
return h;
}
}
解法二
首先进行升序排序,从数组的最后一个元素向前遍历,h从0开始慢慢增加,如果 citatoins[index] > h 则代表存在 h 个值大于 h 的数,当 citatoins[index] <= h 时则代表这个数不可能大于当前的 h 。因此 h 达到了最大值,继续遍历不可能会出现更大的 h 了。
public class Solution {
public static int hIndex(int[] citations) {
Arrays.sort(citations);
int h = 0, index = citations.length - 1;
/*
从最后一个数(也就是最大的数)开始向前遍历,
如果该数的值大于h,则h加一
* */
while(index >= 0 && citations[index] > h){
h++;
index--;
}
return h;
}
}
322

被折叠的 条评论
为什么被折叠?



