【Leetcode】274. H-Index 274. H指数

1

解法

解法一:基于比较的排序

首先把数组排序一下,然后找到一个最大的h,使得nums[n-h]>=h,二分查找即可
这是 O ( n l o g n ) O(nlogn) O(nlogn)

class Solution(object):
    def hIndex(self, citations):
        """
        :type citations: List[int]
        :rtype: int
        """
        citations.sort()
        n = len(citations)
        l,r = 0,n
        while l<r:
            mid = (l+r)>>1
            if mid and citations[n-mid]<mid:
                r = mid
            else:
                l = mid+1
        if r and citations[n-r]<r:
            r -= 1
        return r

解法二:桶排序

这是@powcai 的评论的思路

如果有n个数,那么建立编号为0~nn+1个桶
对于大于等于n的数,都放到编号为n的桶里;其他数放到相应编号的桶里。
现在我们可以知道,如果sum(bins[h:])>=h,那么h就是合法的h值。
所以我们从大到小遍历,来找到最大的h值。
这是 O ( n ) O(n) O(n)

class Solution(object):
    def hIndex(self, citations):
        """
        :type citations: List[int]
        :rtype: int
        """
        n = len(citations)
        cnt = [0]*(n+1)
        for c in citations:
            if c>=n:
                cnt[n]+=1
            else:
                cnt[c]+=1
        p = 0
        for i in xrange(n,-1,-1):
            p += cnt[i]
            if p>=i:
                return i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值