leetcode python H-Index II(Medium)

本文详细解析了LeetCode上H-Index II问题的解决方案,采用二分搜索法在升序数组中高效寻找满足特定条件的h值,即数组中最多有h个数字大于等于h,其余数字均小于h。文章提供了Python实现代码,展示了如何通过调整左右指针,最终确定满足题目要求的最大h值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode python H-Index II(Medium)

问题描述:

从一个升序数组中找到一个数h,这个数h满足的要求是数组中最多有h个数字大于这个数,剩下的数都小于这个数。

Example:

Example:

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, her h-index is 3.
Note:

If there are several possible values for h, the maximum one is taken as the h-index.

Follow up:

This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?

解法(二分搜索法):

由于是升序数组,而且题目要求我们用log的时间复杂度解决这个问题,所以我们想到用二分搜索法。然后我们要找到中间值的比较条件来更新左右指针。中间值在数组中的值和中间值到末尾的长度这两者进行比较,如果中间值大于到末尾的长度,说明这个位置并不是我们要的位置,就假设这个数是h吧,那这个h到末尾的长度小于h明显不和题意吧,我们要使这个间断变大,就要让右指针向左边移动,相反,如果大于等于的话,虽然满足题意了,但是题目要求我们找到最大的h,所以我们把左指针向有移动。

class Solution:
    def hIndex(self, citations: List[int]) -> int:
        if not citations:return 0
        
        left,right = 0,len(citations) - 1
        while left <= right:
            mid = (left + right) // 2
            if citations[mid] >= len(citations) - mid:
                right = mid - 1
            else:
                left = mid + 1
        return len(citations) - left
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值