题目链接
https://leetcode.com/problems/h-index/
心得
挺有意思的题目,算H因子。
首先抽象出H因子的定义,在数组中找到一个数字H,使得数组中至少有H个数字大于等于H,其余的数学小于等于H。
分析题目中给的例子 [3,0,6,1,5] 。很明显H的取值范围是0到5。最暴力的方法就是逐一判断是否满足。那么对于任意一个可能的值,都要遍历一遍数组来判断是否满足H的条件。所以时间复杂度是 O(n2) 。
如果数组是有序数组呢?那么对于任意一个可能的值,用 O(1) 时间就可以判断这个值是否满足H的定义。所以先对数组进行排序,再逐一判断,那么总的时间复杂度就可以降到 O(nlogn) 。
AC代码
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=False)
h = len(citations)
index = 0
while index < len(citations):
if citations[index] >= h:
return h
index += 1
h -= 1
return 0
if __name__ == '__main__':
s = Solution()
print(s.hIndex([3, 0, 6, 1, 5]))