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排序,假设case1: [0, 1, 3, 4, 5, 5, 5],这时正好有4篇引用数至少为4的文章,所以H-index就是4。这一题实际上是在search第一个不满足条件( (n - i) > citat[i] )
如果case2: [0, 1, 3, 5, 5, 5, 5],那么第一个不满足条件的位置是 citat[3] = 5,因为引用数大于等于5的文章只有n-3 = 4篇。这时的H-index就是n-3 = 4。
再例如case3: [100, 100],第一个不满足条件的位置是0,因为显然没有100篇文章被至少引用了100次。所以H-index = n - 0 = 2
注意L21,因为如果发生了case2或者case3,最后的 right 会由于left = right时不满足条件而运行L21,导致right跑到left左边去。所以最后停在第一个不满足条件的index上的是left。
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if not citations:
return 0 n = len(citations)
left = 0
right = n - 1 while left <= right:
i = left + (right - left)/2
if citations[i] == n-i:
return n - i
elif citations[i] < n - i:
left = i + 1
else:
right = i - 1 return n - left