Leetcode 275. H 指数 II

发布于:2024-10-09 ⋅ 阅读:(20) ⋅ 点赞:(0)

1.题目基本信息

1.1.题目描述

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

h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (n 篇论文中)至少 有 h 篇论文分别被引用了至少 h 次。

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

1.2.题目地址

https://leetcode.cn/problems/h-index-ii/description/

2.解题方法

2.1.解题思路

将citations逆序,从0-length-1,最后一个citations[i]>=i对应的i+1即为题解

2.2.解题步骤

第一步,将数组citations进行逆序

第二步,使用二分查找的红蓝染色法+未标记的区间采用左闭右闭方式,找到最后一个citations[i]>=i,对应的i+1即为题解

3.解题代码

Python代码

class Solution:
    # 思路:将citations逆序,从0-length-1,最后一个citations[i]>=i对应的i+1即为题解
    # 第一步,将数组citations进行逆序
    # 第二步,使用二分查找的红蓝染色法+未标记的区间采用左闭右闭方式,找到最后一个citations[i]>=i,对应的i+1即为题解
    def hIndex(self, citations: List[int]) -> int:
        citations.reverse()
        length=len(citations)
        # 红:citation[i]>=i+1,蓝:citation[i]<i+1;左闭右闭:left-1始终指向红色,right+1始终指向蓝色。最终的left即为题解。
        left,right=0,length-1
        while left<=right:
            mid=(right-left)//2+left
            if citations[mid]>=mid+1:
                left=mid+1
            else:
                right=mid-1
        return left

C++代码

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int length=citations.size();
        int left=1,right=length;
        while(left<=right){
            int mid=(right-left)/2+left;
            if(citations[length-mid]>=mid){
                left=mid+1;
            }else{
                right=mid-1;
            }
        }
        return right;
    }
};

4.执行结果

在这里插入图片描述