先讲一下自己的复杂的写法
- 第一眼最大最小值问题,直接在0和最大被引次数之间二分找答案
- 先排序,再二分,,,
正解:
- 排序得到 citations 的递减序列,通过递增下标 i 遍历该序列
- 显然只要排序后的 citations[i] >= i + 1,那么 h 至少是 i + 1,由于 citations[i] 递减,i 递增,所以遍历过程中必有交点,也就是答案
class Solution:
def hIndex(self, citations: List[int]) -> int:
if len(citations) == 0:
return 0
citations.sort()
l, r = 0, citations[-1]
while l < r:
mid = (l + r) >> 1
t = len(citations) - bisect_left(citations, mid)
if t >= mid:
l = mid + 1
if t < mid:
r = mid
t = len(citations) - bisect_left(citations, r)
return r if t >= r else l - 1
class Solution:
def hIndex(self, citations: List[int]) -> int:
sorted_citation = sorted(citations, reverse = True)
h = 0; i = 0; n = len(citations)
while i < n and sorted_citation[i] > h:
h += 1
i += 1
return h