给你一个整数数组 citations
,其中 citations[i]
表示研究者的第 i
篇论文被引用的次数,citations
已经按照 升序排列 。计算并返回该研究者的 h
指数。
h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h
指数是指他(她)的 (n 篇论文中)总共有 h
篇论文分别被引用了至少 h
次。
请你设计并实现对数时间复杂度的算法解决此问题。
示例 1:
输入:
citations = [0,1,3,5,6]
输出:3
解释:给定数组表示研究者总共有5
篇论文,每篇论文相应的被引用了0, 1, 3, 5, 6
次。由于研究者有3
篇论文每篇 至少 被引用了3
次,其余两篇论文每篇被引用 不多于 3 次,所以她的h
指数是 3 。
示例 2:
输入:
citations = [1,2,100]
输出:2
提示:
n == citations.length
1 <= n <= 10^5
0 <= citations[i] <= 1000
citations
按 升序排列
题目来源:https://leetcode.cn/problems/h-index-ii/description/
解题方法:
方法一:从后往前遍历
class Solution {/*** @param Integer[] $citations* @return Integer*/function hIndex($citations) {$n = count($citations);$h = 1;for ($i = $n - 1; $i >= 0; $i--) {$c = $citations[$i];if ($c >= $h) {$h++;} else {break;}}return $h - 1;}
}
参考:https://leetcode.cn/problems/h-index-ii/solutions/871136/275wo-wei-phptian-zhuan-jia-wa-by-hikomi-xdr9/
方法二:二分法查找
class Solution {/*** @param Integer[] $citations* @return Integer*/function hIndex($citations) {$citations[] = 0; //添加一个元素到末尾,当原数组只有一个元素时做取中操作$left = 0;$right = count($citations) - 1;while ($left <= $right) {$mid = floor(($left + $right) / 2);$cnt = 0;foreach ($citations as $num) {if ($num >= $mid) {$cnt++;}}if ($mid <= $cnt) {$left = $mid + 1;} else {$right = $mid - 1;}}return $right;}
}
参考:https://leetcode.cn/problems/h-index-ii/solutions/870948/er-fen-by-si-haanatawo-0nxl/