码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode H-index

时间:2016-12-15 07:33:53      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:tps   使用   ref   init   min   复杂度   type   http   长度   

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."

For example, given citations = [3, 0, 6, 1, 5], which 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, his h-index is 3.

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

 

先对citations 排序,比较citations[i] 和 n - i, 一个是引用数,一个是至少被引用了这么多次的paper的数量。 h-index应该是二者比较小的那一个。 而且如果citations[i] < n - i , 那么应该检查下一个citations[i+1]是不是满足这个条件。

 1 class Solution(object):
 2     def hIndex(self, citations):
 3         """
 4         :type citations: List[int]
 5         :rtype: int
 6         """
 7         if not citations:
 8             return 0
 9         citations.sort()
10         n = len(citations)
11         h_index = 0
12         for i in range(n):
13             cur = min(citations[i], n - i)
14             if cur > h_index:
15                 h_index = cur
16         return h_index

或者

 1 def hIndex(self, citations):
 2         """
 3         :type citations: List[int]
 4         :rtype: int
 5         """
 6         if not citations:
 7             return 0
 8         citations.sort()
 9         n = len(citations)
10         h_index = 0
11         for i in range(n):
12             if citations[i] < n - i:
13                 h_index = citations[i]
14             else:
15                 return n - i
16         return h_index

如果citations已经是排序好了的。可以使用二分法使得搜索的复杂度变成O(longN)

 1 def hIndex(self, citations):
 2         """
 3         :type citations: List[int]
 4         :rtype: int
 5         """
 6         
 7         if not citations:
 8             return 0
 9         n = len(citations)
10         left = 0
11         right = n-1
12         
13         while left <= right:
14             mid = (left + right)//2
15             if citations[mid] < n - mid:
16                 left = mid + 1
17             else:
18                 right = mid - 1
19         
20         return n - left

 L13如果不加这个等号,对于长度=1的citations list会出错。

Leetcode H-index

标签:tps   使用   ref   init   min   复杂度   type   http   长度   

原文地址:http://www.cnblogs.com/lettuan/p/6181810.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!