刷题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
原创粉丝点击