Python AC code for h index calculation


  • -1
    B
    class Solution(object):
        def hIndex(self, citations):
            """
            :type citations: List[int]
            :rtype: int
            """
            if not citations:
                return 0
            citations.sort()
            h_index = 0
            size = len(citations)
            for i in range(size):
                try_index = size - i
                if citations[i] >= try_index and (i < 1 or citations[i - 1] <= try_index):
                    h_index = max(h_index , try_index)
                    
            return h_index

  • 0
    H
    class Solution(object):
        def hIndex(self, citations):
            """
            :type citations: List[int]
            :rtype: int
            """
            N = len(citations)
            if N == 0:
                return 0
            sortlist = sorted(citations, reverse = True)
            #
            i = 0
            while i<N and sortlist[i] >= (i+1):
                i += 1
            return i
    

    ############################
    The idea:
    If we sort all the citations in decreasing order to sortlist, and index each citation number by 1, 2, 3, ..., then we can find the h-index is the max value i, which makes sortlist[i]>=i.


  • 0
    W

    I have another way to solve this one and much easier to understand

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.