题目:
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).
分析:
- 通过集合运算获得所有元素唯一的列表,时间复杂度为O(n)
- 将新列表长度小于等于3,作为特例处理
- 采用选择排序算法,由于只获取第三大的值,因此此过程时间复杂度为O(n)
代码:
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret = 0
uniqueNums = list(set(nums))
if len(uniqueNums) < 3:
return max(uniqueNums)
if len(uniqueNums) == 3:
return min(uniqueNums)
for i in range(3):
for j,x in enumerate(uniqueNums[1:]):
if uniqueNums[j] > uniqueNums[j + 1]:
uniqueNums[j],uniqueNums[j + 1] = uniqueNums[j + 1],uniqueNums[j]
ret = uniqueNums.pop()
return ret
思考: