给你一个整数数组 citations
,其中 citations[i]
表示研究者的第 i
篇论文被引用的次数。计算并返回该研究者的 h
指数。
根据维基百科上 h 指数的定义:h 代表“高引用次数”,一名科研人员的 h
指数是指他(她)的 (n
篇论文中)总共有 h
篇论文分别被引用了至少 h
次。且其余的 n - h
篇论文每篇被引用次数 不超过 h
次。
如果 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
错误思路:
总结一下我一开始做这道题的错误思路。
public static int hIndex(int[] citations) {
int key=citations.length;
int result=GetH(citations,key);
while (true){
if (result>key){break;}
else{
key--;
result=GetH(citations,key);
}
}
return result;
}
public static int GetH(int[] citations,int key){
int Account=0;
for (int citation : citations) {
if (citation >= key) Account++;
}
return Account;
}
一开始我使用递归,从后往前求,但是这种方法只能求像例一这种情况,即被引用多余h次的论文刚好是h篇,而第二种小于h的例子就无法运算。
正确方法:
public static int hIndex(int[] citations) {
quickSort(citations);
int h=0;
int i=citations.length-1;
while (i>=0&&citations[i]>h){
h++;
i--;
}
return h;
}
private static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
private static void subSort(int[] data, int start, int end) {
if (start < end) {
int base = data[start];
int low = start;
int high = end + 1;
while (true) {
while (low < end && data[++low] - base <= 0)
;
while (high > start && data[--high] - base >= 0)
;
if (low < high) {
swap(data, low, high);
} else {
break;
}
}
swap(data, start, high);
subSort(data, start, high - 1);//递归调用
subSort(data, high + 1, end);
}
}
public static void quickSort(int[] data){
subSort(data,0,data.length-1);
}
先将数组按小到大排序(为了追求速度,这里我用了快排),我们通过这个可以找到最接近查找数的论文数量。这个就是我们要找的最大值。