题目描述
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher’s h-index.
According to the definition of h-index on Wikipedia: “A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each.”
给一个升序数组,代表一个研究人员每篇文章的引用次数,求这个研究人员的H指数。H指数代表这个研究人员至少有H篇文章被至少引用了H次,返回所有可能H值中最大的一个。
样例
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
算法1
题解:首先这个人的H指数肯定是在[0,nums.size()]之间的,这个题目可以看作是求所有H值中最大的那个,但是我们可以反向思考一下。如下:
index = [0,1,2,3,4]//数组下标
citation = [0,1,3,5,6]//citation[i]代表第i篇论文的引用次数
count = [5,4,3,2,1]//count[i]代表至少有多少篇文章引用了引用了citation[i]次
其他例子
// [0,0,4,4]
// [4,3,2,1]
// [0,0,0,0]
// [4,3,2,1]
// [5,6,7,8]
// [4,3,2,1]
那么问题其实可以转化成求所有citation[i]>=count[i]中最小的那个i对应的count[i],这样问题就转换成二分查找模板二 的问题了,求使条件成立的最小的i。如果没有任何一个i满足,则说明这个人的H值应该为0。这里count[i] = n - i。
数组是升序的可以直接判断最后一个元素如果是0,那么返回0,否则至少有一篇文章引用了被引用过,H≥1
C++ 代码
int hIndex(vector<int>& citations) {
int n = citations.size();
if(n == 0 || citations[n - 1] == 0) return 0;
int left = 0,right = n - 1;
while(left < right)
{
int mid = (left + right) / 2;
if(citations[mid] >= n - mid) right = mid;
else left = mid + 1;
}
return n - left;
}
这个转化的逻辑写的很好!点赞,留言hhh!
谢谢支持