Description
Given an array of citations (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."
For example, given citations = [3, 0, 6, 1, 5]
, which means the researcher has 5
papers in total and each of them had received 3, 0, 6, 1, 5
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, his h-index is 3
.
Note: If there are several possible values for h
, the maximum one is taken as the h-index.
Solution
题目理解很直观,即找到一个数h,使得有h篇论文的引用大于h,其余论文的引用数小于等于h。
其解题思路如下:
① 预处理:为了快速对h进行判断,对整个数组进行了排序。
② 二分,每次对中间节点判断右侧节点个数是否为有效的h-index:
i. 若中间节点值小于右侧节点个数,则h-index必然存在于当前中点右侧,令begin = middle + 1。
ii.若中间节点值大于等于右侧节点个数,则结合中点前一个节点进行判断:
a. 如果前一个节点的坐标小于0或值小于等于候选h-index,则h-index有效,跳出二分查找。
b. 如果前一个节点的值大于候选h-index,则h-index必然存在于当前中点左侧,令end = middle - 1。
代码实现如下:
class Solution {
public:
int hIndex(vector<int>& citations) {
// 结果
int result = 0;
// 排序
sort(citations.begin(), citations.end());
// 二分确定hindex
int begin = 0;
int end = citations.size() - 1;
while (begin <= end) {
int middle = (begin + end) / 2;
int cit = citations.size() - middle;
if (citations[middle] < cit)
begin = middle + 1;
else if (citations[middle] >= cit) {
if (middle - 1 < 0 || citations[middle - 1] <= cit) {
result = cit;
break;
}
else if (citations[middle - 1] > cit)
end = middle - 1;
}
}
return result;
}
};
运行结果如下: