跳至主要內容

275. H 指数 II


275. H 指数 IIopen in new window

🟠   🔖  数组 二分查找  🔗 力扣open in new window LeetCodeopen in new window

题目

Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in ascending order , return the researcher 's h-index.

According to the definition of h-index on Wikipediaopen in new window: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.

You must write an algorithm that runs in logarithmic time.

Example 1:

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, their h-index is 3.

Example 2:

Input: citations = [1,2,100]

Output: 2

Constraints:

  • n == citations.length
  • 1 <= n <= 10^5
  • 0 <= citations[i] <= 1000
  • citations is sorted in ascending order.

题目大意

给你一个整数数组 citations ,其中 citations[i] 表示研究者的第 i 篇论文被引用的次数,citations 已经按照 升序排列 。计算并返回该研究者的 h 指数

根据维基百科上 h 指数的定义:h 代表“高引用次数” ,一名科研人员的 h 指数 是指他(她)至少发表了 h 篇论文,并且 至少h 篇论文被引用次数大于等于 h 。如果 h 有多种可能的值,h 指数 是其中最大的那个。

请你设计并实现对数时间复杂度的算法解决此问题。

示例 1:

输入:citations = [0,1,3,5,6]

输出:3

解释:给定数组表示研究者总共有 5 篇论文,每篇论文相应的被引用了 0, 1, 3, 5, 6 次。

由于研究者有 3 篇论文每篇 至少 被引用了 3 次,其余两篇论文每篇被引用 不多于 3 次,所以她的 h 指数是 3。

示例 2:

输入:citations = [1,3,100]

输出:2

解题思路

第 274 题 相比,这道题中的输入数组 citations 已经按照升序排序。题目要求实现对数时间复杂度的算法,可以联想到使用二分查找的方法求解。

设查找范围的初始左边界 left0, 初始右边界 rightn−1,其中 n 为数组 citations 的长度。每次在查找范围内取中点 mid,则有 n−mid 篇论文被引用了至少 citations[mid] 次。如果在查找过程中满足 citations[mid]≥n−mid,则移动右边界 right,否则移动左边界 left

复杂度分析

  • 时间复杂度O(log n)
  • 空间复杂度O(1)

代码

/**
 * @param {number[]} citations
 * @return {number}
 */
var hIndex = function (citations) {
	let n = citations.length,
		left = 0,
		right = n - 1;
	while (left <= right) {
		const mid = (left + right) >> 1;
		if (citations[mid] >= n - mid) {
			right = mid - 1;
		} else {
			left = mid + 1;
		}
	}
	return n - left;
};

相关题目

题号标题题解标签难度
274H 指数open in new window[✓]数组 计数排序 排序