leetcode python H-Index II(Medium)
问题描述:
从一个升序数组中找到一个数h,这个数h满足的要求是数组中最多有h个数字大于这个数,剩下的数都小于这个数。
Example:
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 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.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
解法(二分搜索法):
由于是升序数组,而且题目要求我们用log的时间复杂度解决这个问题,所以我们想到用二分搜索法。然后我们要找到中间值的比较条件来更新左右指针。中间值在数组中的值和中间值到末尾的长度这两者进行比较,如果中间值大于到末尾的长度,说明这个位置并不是我们要的位置,就假设这个数是h吧,那这个h到末尾的长度小于h明显不和题意吧,我们要使这个间断变大,就要让右指针向左边移动,相反,如果大于等于的话,虽然满足题意了,但是题目要求我们找到最大的h,所以我们把左指针向有移动。
class Solution:
def hIndex(self, citations: List[int]) -> int:
if not citations:return 0
left,right = 0,len(citations) - 1
while left <= right:
mid = (left + right) // 2
if citations[mid] >= len(citations) - mid:
right = mid - 1
else:
left = mid + 1
return len(citations) - left