Leetcode 274, 275 Hi-index I and II
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。
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 10 n = len(citations) 11 left = 0 12 right = n - 1 13 14 while left <= right: 15 i = left + (right - left)/2 16 if citations[i] == n-i: 17 return n - i 18 elif citations[i] < n - i: 19 left = i + 1 20 else: 21 right = i - 1 22 23 return n - left