H指数 I
链接:link
方法一:排序
- 对列表进行排序,遍历排序后的列表,直到找到一个引用次数小于当前索引值的论文。
- 假设当前索引值为 i i i,引用次数为 c i t a t i o n s [ i ] citations[i] citations[i],因为数组是有序的,所以 i i i之后的文章的被引用次数都是大于 c i t a t i o n s [ i ] citations[i] citations[i]的,则即被引用次数大于等于 c i t a t i o n s [ i ] citations[i] citations[i]的至少有 l e n g t h − i length - i length−i,所以应该有 c i t a t i o n s [ i ] ≥ l e n g t h − i citations[i] ≥ length - i citations[i]≥length−i
- 时间复杂度 O ( n l o g n ) O(nlogn) O(nlogn),,空间复杂度 O ( l o g n ) O(logn) O(logn)
代码
public int hIndex(int[] citations) {
Arrays.sort(citations);
int length = citations.length, h = 0;
for(int i = 0; i < length; i++) {
if(citations[i] >= length -i ){
return length - i;
}
}
return h;
}
方法二:计数排序
- 使用一个长度为 n + 1 n+1 n+1 的数组 c o u n t e r counter counter ,其中 c o u n t e r [ i ] counter[i] counter[i] 表示引用次数为 i i i 的论文的篇数。
- 可以发现 H H H 指数不可能大于总的论文发表数 n n n,遍历数组 c i t a t i o n s citations citations ,将引用次数大于等于 n n n 的论文都当作引用次数为 n n n 的论文,然后将每篇论文的引用次数作为下标,将 c o u n t e r [ i ] counter[i] counter[i] 中对应的元素值加1。这样就统计出了每个引用次数对应的论文篇数。
- 接下来,从大到小枚举 h h h 值,将 c o u n t e r counter counter 中下标为 h h h 的元素值加到变量 s s s 中,其中 s s s 表示引用次数大于等于 h h h 的论文篇数。如果 s ≥ h s≥h s≥h,说明至少有 h h h 篇论文分别被引用了至少 h h h 次,直接返回 h h h即可。
代码
public int hIndex(int[] citations) {
int n = citations.length;
int[] counter= new int[n + 1];
for (int x : citations) {
//比如[3,0,6,1,5],一开始n为5,x为3,第一个元素为x,应该是更新引用次数大于等于3的情况
++cnt[Math.min(x, n)];
}
for (int h = n, s = 0; --h) {
s += counter[h];
if (s >= h) {
return h;
}
}
}
H指数 II
链接:link
数组有序,就不要再排序了
代码
public int hIndex(int[] citations) {
int length = citations.length, h = 0;
for(int i = 0; i < length; i++) {
h = Math.max(h, Math.min(length-i, citations[i]));
}
return h;
}