1. 程式人生 > >Leetcode_Sort --274. H-Index [medium]

Leetcode_Sort --274. H-Index [medium]

Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher’s h-index. According to the definition of h-index on Wikipedia: “A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than

h citations each.” 給定一個學者的文章引用數列表,寫一個方程來計算學者的h-index h-index定義為一個學者的文章引用數中,有h篇文章的引用數至少為h,剩下的引用數都是不多於h的 Example:

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

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

Solution:

Python

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

解題思路: 本題其實很簡單,這個題目抽象出來就是在陣列中找到h個大於h的數(這裡我覺得是有歧義的,英文中先說at least h citations each,也就是包含h,而後面又說 no more then ,從結果來判斷,應該是h個大於h的數),剩下的數都不大於h。這裡的h應該從0開始,我們先將陣列進行降序排列,依次將陣列中的數和h進行比較,當陣列中的數大於h的時候,h就加一,然後再與陣列的下一個數進行比較,直到陣列遍歷完成,返回h即可。