Tag: Array
Difficult: Easy
Description:
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 2:
Input: [1, 2]
Output: 2
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Code: (条件语句分支讨论)
import sys
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
first = -sys.maxint
second = -sys.maxint
third = -sys.maxint
for n in nums:
if n>first:
third = second
second = first
first = n
elif n<first:
if n>second:
third = second
second = n
elif n<second:
if n>third:
third = n
if third!=-sys.maxint:
return third
else:
return first