0274-h-index

Try it on leetcode

Description

Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index.

According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.

 

Example 1:

Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 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, their h-index is 3.

Example 2:

Input: citations = [1,3,1]
Output: 1

 

Constraints:

  • n == citations.length
  • 1 <= n <= 5000
  • 0 <= citations[i] <= 1000

Solution(Python)

class Solution:
    def hIndex(self, citations: List[int]) -> int:
        # citations = [3,0 6,1,5]
        # h number of papers <= h
        #  range : 0...n
        #  h= 1
        #    0 1 3 5 6
        #    no
        #  h =2
        #    3 <= 2 false
        #  h =3 
        #    3<=3 True
        #  sorted  find the partition where h >= number of parers form right
        #   
        #  3 0 6 1 5
        #  after sorting: 6 5 3 1 0
        #   h   h +1  citaitions      condition      res
        #   0     1    6           6>= 1            1
        #   1      2    5           5>=1            2
        #   2       3   3           3>=1            3
        #   4       5   1           2>=5            3
        #   5       6   0            1>=6           3
        #  
        #   1 1 1 1 1 
        #  0    1   1     1>=1  1
        #  1    2   1     1>=2  1
        #  2    3   1     
        n = len(citations)
        if n == 0:
            return 0
        citations.sort(reverse=True)
        res = 0
        for h in range( n):
            if citations[h] >= h + 1 :
                res = h + 1
            else:
                return res
        return res

        

Dry Run