LeetCode 414. third largest number (python)

Topic Link

Description Title:
given a non-empty array, this array returns the third largest number. If not, the maximum number of array is returned. Request time complexity of the algorithm must be O (n).

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third number is 1.
Example 2:

Input: [1, 2]

Output: 2

Explanation: third number does not exist, it returns the largest number 2.
Example 3:

Input: [2, 2, 3, 1]

Output: 1

Explanation: Note, asked to return to the third largest number it refers to the third largest and the only number that appears.
There are two values of the number of 2, they are ranked second.

Outline of Solution:
Python with float ( "inf"), float ( "- inf") indicate positive and negative infinity
respectively provided m, mm, mmm, negative infinity is used to represent the largest, the second largest, the three figures
traverse nums,
if the number is greater than the largest current, the current largest digital set, and the original first major, the second largest were changed to the second largest, third
and so on

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        mmm,mm,m=float('-inf'), float('-inf'),float('-inf')
        for i in nums:
            if i>m:
                m,mm,mmm=i,m,mm
            elif m>i>mm:
                mm,mmm=i,mm
            elif mm>i>mmm:
                mmm=i
        return m if mmm== float('-inf') else mmm

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_44740082/article/details/90812923