题目:
给你一个整数数组 citations ,其中 citations[i] 表示研究者的第 i 篇论文被引用的次数。计算并返回该研究者的 h 指数。
根据维基百科上 h 指数的定义:h 代表“高引用次数” ,一名科研人员的 h 指数 是指他(她)至少发表了 h 篇论文,并且每篇论文 至少 被引用 h 次。如果 h 有多种可能的值,h 指数 是其中最大的那个。
题目链接:https://leetcode.cn/problems/h-index/
题解:
- h数的含义为:有h篇论文的引用次数至少为h,题目要求我们查找h的最大值。
- 我们可以很简单地判断某个数n是否为h。只需遍历数组,统计满足citations[i]>=n的数,若总数大于等于n,则满足。
- 若n是h,则所有小于n的数也是h;若n不为h,则大于n的数一定不为h。显然,若有h篇论文的引用次数至少为h,一定有有h-1篇论文的引用次数至少为h-1,反之亦然。
- 基于此,我们可以进行二分查找。每次取中位数mid,若mid为h,则小于mid的数一定为h,说明要寻找的h在[h,end]中;若mid不为h,则大于mid的数一定不为h,说明要寻找的h在[start,h)中。
- qs:不要困在citations数组中,h的值在[0,citationsSize]中取得,即小于等于论文总数。
bool isH(int* citations,int citationsSize,int h){
int n=0;
for(int i=0;i<citationsSize;i++){
if(citations[i]>=h) n++;
}
if(n<h) return 0;
return 1;
}
int hIndex(int* citations, int citationsSize){
int start=0;
int end=citationsSize;
int h=(end+1)/2;
for(;start<end;){
if(isH(citations,citationsSize,h)) {
start=h;
h=(start+end+1)/2;
} else{
end=h-1;
h=(start+end+1)/2;
}
}
return h;
}
时间复杂度:O(nlogn),其中 n 为数组长度。需要进行 logn 次二分搜索,每次二分搜索需要遍历数组一次。
空间复杂度:O(1),只需要常数个变量来进行二分搜索。