原题链接:275. H-Index II
【思路-Java、Python】 二分查找 T=O(logn)|M=O(1)
本题是基于 leetcode 274. H-Index-h因子|哈希表,如果对于 h-index 概念不是很理解的可以参考这篇博文。
本题采用二分查找进行
public class Solution {
public int hIndex(int[] citations) {
int level = 0, n = citations.length, left = 0, right = n - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(citations[mid] >= n - mid) { //一旦发现引用次数大于 n-mid,就在左半部查找可能更大的 level
level = n - mid;
right = mid - 1;
}
else left = mid + 1; //说明左半部没有更大的 level,则在右半部查找
}
return level;
}
}
82 / 82
test cases passed. Runtime: 11 ms Your runtime beats 67.83% of javasubmissions.
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
level, n, left, right = 0, len(citations), 0, len(citations) - 1
while left <= right :
mid = (left + right) / 2
if citations[mid] >= n - mid :
level = n - mid
right = mid - 1
else : left = mid + 1
return level
82 / 82
test cases passed. Runtime: 152 ms Your runtime beats 28.13% of pythonsubmissions.