274-275. H-Index I & II [Medium]

2019-06-01  本文已影响0人  一个想当大佬的菜鸡
274. H-Index

O(nlogn)
先逆序排序,第i个,引用次数citations[i],大于等于此citations的文章数i+1,curh是两者的最小,h是所有h的最大

class Solution(object):
    def hIndex(self, citations):
        """
        :type citations: List[int]
        :rtype: int
        """
        citations.sort(reverse=True)
        h = 0
        for i in range(len(citations)):
            curh = min(citations[i], i+1)
            h = max(h, curh)
        return h

O(n),用一个数组长(n+1),记录引用次数,从后往前,当前引用是i,大于等于此引用次数的文章数是curCit,返回最小的那个

class Solution(object):
    def hIndex(self, citations):
        """
        :type citations: List[int]
        :rtype: int
        """
        temp = [0] * (len(citations) + 1)
        for i in citations:
            if i > len(citations):
                temp[-1] += 1
            else:
                temp[i] += 1
        curCit = 0
        for i in range(len(citations),-1,-1):
            curCit += temp[i]
            if curCit >= i:
                return i
        return 0

275和274一模一样,只不过给了排好序的。

上一篇下一篇

猜你喜欢

热点阅读