【LeetCode】274. H 指数

274. H 指数

题目

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

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

示例

示例 1:

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

输出:3

解释:给定数组表示研究者总共有 5 篇论文,每篇论文相应的被引用了 3, 0, 6, 1, 5 次。
由于研究者有 3 篇论文每篇 至少 被引用了 3 次,其余两篇论文每篇被引用 不多于 3 次,所以她的 h 指数是 3。

示例 2:

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

输出:1

解法

解法一:遍历所有可能性

public int hIndex(int[] citations) {
     if (citations == null || citations.length <= 0)
          return 0;

     int count = 0;
     for (int h = 1; h <= citations.length; h++) {
          count = 0;
          for (int i = 0; i < citations.length; i++) {
               if (citations[i] >= h) {
               count++;
               }
          }
          if (count < h) {
               return h - 1;
          }
     }
     return count;
}

时间复杂度:O(n^2)
空间复杂度:O(1)

解法二

二分搜索

public int hIndex(int[] citations) {
     if (citations == null || citations.length <= 0)
          return 0;

     int left = 0, right = citations.length;
     int mid = 0, cnt = 0;
     while (left < right) {
          mid = (left + right + 1) >> 1;
          cnt = 0;
          for (int i = 0; i < citations.length; i++) {
               if (citations[i] >= mid) {
               cnt++;
               }
          }
          if (cnt >= mid) {
               // 要找的答案在 [mid,right] 区间内
               left = mid;
          } else {
               // 要找的答案在 [0,mid) 区间内
               right = mid - 1;
          }
     }
     return left;
}
posted @ 2025-10-12 18:03  WilsonPan  阅读(7)  评论(0)    收藏  举报