1、题目描述
给你一个整数数组 citations ,其中 citations[i] 表示研究者的第 i 篇论文被引用的次数,citations 已经按照 升序排列 。计算并返回该研究者的 h 指数。
h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (n 篇论文中)总共有 h 篇论文分别被引用了至少 h 次。且其余的 n - h 篇论文每篇被引用次数 不超过 h 次。
提示:如果 h 有多种可能的值,h 指数 是其中最大的那个。
要求:请你设计并实现对数时间复杂度的算法解决此问题。
2、样例输出
3、思路分析
这道题是「 H 指数」的延伸,与之相比,这道题中的输入数组 citations 已经按照升序排序。
这道题可以利用数组 citations 有序的特点,使用二分查找的方法求解,时间复杂度为 O(logn),其中 n 为数组 citations 的长度。
设查找范围的初始左边界 left 为 0, 初始右边界 right 为 n−1,其中 n 为数组 citations 的长度。每次在查找范围内取中点 mid,则有 n − mid 篇论文被引用了至少 citations[mid] 次。如果在查找过程中满足 citations[mid] ≥ n − mid,则移动右边界 right,否则移动左边界 left。
class Solution {
public int hIndex(int[] citations) {
int n = citations.length;
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (citations[mid] >= n - mid) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return n - left;
}
}
4、复杂度分析
1)时间复杂度
O(logn),其中 n 为数组 citations 的长度。二分查找的时间复杂度为 O(logn)
2)空间复杂度
O(1),使用常数额外空间,存放临时变量