414. Third Maximum Number

https://leetcode.com/problems/third-maximum-number/#/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 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.


Sol:

Establish a list v,with three elements to store the largest, second largest and third largest number of the array. Traverse the array and check if the current number is larger than the first element in v, and put the larger number to the first place of list v. Then compare the current value to the second element in  list v and get the larger one to the second place of list v. Do this to third element in list v for the third time. In this way, we make sure:

v = [largest number, second largest number, third largest number]

return v[2] 

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        # if len(nums) == 0:
        #    return None
        # elif len(nums) < 3:
        #    return max(nums)
        #else:
        v = [float('-inf'), float('-inf'), float('-inf')]
        for num in nums:
            if num not in v:
                if num > v[0]:
                    v = [num, v[0],v[1]]
                elif num > v[1]:
                    v = [v[0], num, v[1]]
                elif num > v[2]:
                    v = [v[0], v[1], num]
        if float('-inf') in v:
            return max(nums)
        return v[2]

Note:

1 Make a list of three variables and keep comparing the current number with the current v[0], v[1] and v[2] and updating list v is the real trick here. 

原文地址:https://www.cnblogs.com/prmlab/p/6971500.html