Problem: 274. H 指数
每日一题。
思路
理解关系,至少i篇论文引用至少i次,其余len-n篇引用不超过i次。
排序(某条分界线右边满足题意)(可二分查找[1,2,3,4,5]),计数。
Code
数组计数
class Solution {
public int hIndex(int[] citations) {
int len = citations.length;
int[] count = new int[len+1]; // 含len+1计数
// 记录引用次数
for(int i:citations){
count[Math.min(i,len)]++;// 引用次数超过h范围取len
}
// 后向前
for(int i=len,sum=0;i>=0;i--){
sum += count[i];
if(sum>=i){
return i;// 至少i篇论文引用次数至少为i
}
}
return -1;
}
}
排序+后向前遍历
class Solution {
public int hIndex(int[] citations) {
int n = citations.length;
int h = 0;
Arrays.sort(citations);
for (int i = n - 1; i >= 0; i--) {
// 当前论文的引用次数大于等于 h 时,满足 h 指数的定义
if (citations[i] >= h + 1) {
h++;
} else {
// 如果当前论文引用次数小于 h,后面的论文引用次数一定更小
// 因此可以提前结束遍历,返回当前的 h 指数
break;
}
}
return h;
}
}