LeetCode刷题 (Python) | 274. H-Index
2016-02-10 14:35
796 查看
题目链接
https://leetcode.com/problems/h-index/心得
挺有意思的题目,算H因子。首先抽象出H因子的定义,在数组中找到一个数字H,使得数组中至少有H个数字大于等于H,其余的数学小于等于H。
分析题目中给的例子 [3,0,6,1,5][3, 0, 6, 1, 5]。很明显H的取值范围是0到5。最暴力的方法就是逐一判断是否满足。那么对于任意一个可能的值,都要遍历一遍数组来判断是否满足H的条件。所以时间复杂度是O(n2)O(n^2)。
如果数组是有序数组呢?那么对于任意一个可能的值,用O(1)O(1)时间就可以判断这个值是否满足H的定义。所以先对数组进行排序,再逐一判断,那么总的时间复杂度就可以降到O(nlogn)O(n\log n)。
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]))
相关文章推荐
- Chapter12_Advanced_Numpy
- Python 16.2 使用MySQL
- windows中安装python
- windows中安装python
- Python eval函数
- python核心编程-第六章习题答案
- python 使用requests第三方库自动登陆新浪微博
- [Python for Data Analysis] Python Basic--Function
- [Python for Data Analysis]Python Basic2--Data Structure and Sequences
- python学习笔记——文件操作
- Notes of Python Learning 2/10/2016
- 安装numpy,scipy,matplotlib的好去处
- python实现井字棋游戏
- python学习笔记
- python下numpy不成功,请问有没有简单的安装方法?
- python入门笔记(Day8)--StringIO,BytesIO,环境变量, 操作文件和目录
- Python图像处理库PIL的基本概念介绍
- python算法之二分查找
- python搭建微信公众平台
- 【Python 笔记】文件读写