Skip to content

Latest commit

 

History

History
67 lines (46 loc) · 1.57 KB

0414. Third Maximum Number.md

File metadata and controls

67 lines (46 loc) · 1.57 KB

题目

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.

我的思路

这道题要求取出给定数组中第三大的数字,并且重复的数字只算一个,若没有第三大的数字就输出最大的数字。我用三个变量来保存前三大的数字,初始化时将这三个数初始化为32位最小的int再减1。

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        a,b,c = -2147483649, -2147483649, -2147483649
        for x in nums:
            if x == a or x == b or x == c:
                continue
            if x > c:
                if x > b:
                    if x > a:
                        c = b
                        b = a
                        a = x
                        continue
                    c = b
                    b = x
                    continue
                c = x            
        if c != -2147483649:
            return c
        else:
            return a