题目
给定一位研究者论文被引用次数的数组(被引用次数是非负整数)。编写一个方法,计算出研究者的 h 指数。
h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (N 篇论文中)总共有 h 篇论文分别被引用了至少 h 次。且其余的 N - h 篇论文每篇被引用次数 不超过 h 次。
例如:某人的 h 指数是 20,这表示他已发表的论文中,每篇被引用了至少 20 次的论文总共有 20 篇。
示例:
输入:citations = [3,0,6,1,5]
输出:3
解释:给定数组表示研究者总共有 5 篇论文,每篇论文相应的被引用了 3, 0, 6, 1, 5 次。
由于研究者有 3 篇论文每篇 至少 被引用了 3 次,其余两篇论文每篇被引用 不多于 3 次,所以她的 h 指数是 3。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/h-index
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
排序遍历
最直接的方法就是对citations进行排序,然后从大到小遍历,直到找到文章数与引用数一致的最大值并返回这个值:
代码:
class Solution {
public:
int hIndex(vector<int>& citations) {
int validArticle=citations.size()-1;
int hVal = 0;
sort(citations.begin(), citations.end());
while (validArticle >= 0 && citations[validArticle] > hVal)
{
validArticle --;
hVal ++;
}
return hVal;
}
};
复杂度:
排序需要log(n)时间复杂度。遍历最坏情况下需要o(n),所以最终的时间复杂度为O(nlogn)
二分查找
这里可以发现h的可能最大值是citations的长度,我们只需要在【0,n】里找到最大的满足条件的值就可以了(n是citations的长度)需要满足的条件就是引用数和文章数一致。这里只有小于等于n的满足条件,大于n的不满足。这样是满足二段性的,所以可以试着用二分法来找到结果。
代码:
class Solution {
public:
int hIndex(vector<int>& citations) {
int l = 0;
int r = citations.size();
while (l < r)
{
int mid = (l+r+1)/2;
if (validCheck(citations, mid))
{
// mid is a valid h value
// shift left boundary, check for larger value
l = mid;
}
else
{
// mid is not a valid value
// shift right boundary for smaller value
r = mid-1;
}
}
return r;
}
// check if cur mid is a valid h value
bool validCheck(vector<int>& citations, int target)
{
int count = 0;
for(int n: citations)
{
// n is larger equal than mid, it means
if (n>=target)
{
count ++;
}
}
// if there are same or more number of articles as cur target value
return count >= target;
}
};
引用:
https://leetcode-cn.com/problems/h-index/
https://leetcode-cn.com/problems/h-index/solution/gong-shui-san-xie-li-yong-er-duan-xing-z-1jxw/
https://leetcode-cn.com/problems/h-index/solution/h-zhi-shu-by-leetcode-solution-fnhl/