刷题2
来源:互联网 发布:淘宝中专毕业证复印件 编辑:程序博客网 时间:2024/06/07 18:43
python刷Leetcode: Third Maximum Number
题目描述:
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
题目要求时间复杂度在O(n), 感觉这就不能随便用max()函数,查了一下python中max()的时间复杂度在O(n).
不考虑这个要求的话,第一个思路用set(),然后依次删除最大(操作两次)。
def thirdMax(self, nums): nums = set(nums) if len(nums) < 3: return max(nums) nums.remove(max(nums)) nums.remove(max(nums)) return max(nums)
如果考虑时间复杂度,那就得挨个比了,先确定三个最大值,然后挨个比较list元素,重新确定最大的三个值:
import sysclass Solution(object): def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ one = two = three = -sys.maxint for i in nums: if i > one: one, two, three = i, one, two elif i > two and i < one: two, three = i, two elif i > three and i < two: three = i return three if three != -sys.maxint else one
- 刷题2
- [刷题]2 Sum
- 剑指offer刷题(2)
- LeetCode刷题(2)
- Leetcode刷题(2)
- [刷题#2][FJOI2015]建筑师
- leetcode刷题(2)
- LeetCode刷题(2)
- leetcode刷题-堆栈2
- 刷题
- 刷题
- 刷题
- 刷题
- 刷题
- 刷题。。。
- 刷题
- 刷题
- 刷题
- hihoCoder 最大权闭合子图
- 第一次写博客,不知道标题写什么好。
- linux下查找某个目录下包含某个字符串的文件
- keil里面骚气的printf
- 避免按钮重复点击
- 刷题2
- 插入法建立一个最大堆
- C++ 异常处理
- ubuntu14.04一键安装eclipse和CDT
- hdu2952 Counting Sheep 深搜
- TortoiseSVN安装及导入已有SVN仓库
- Linux基础
- java数据类型
- 在一个有序数列中找到第一个比x大的数的位置