Homework (12) - 414. Third Maximum Number

topic

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.


ideas

    Traverse the list like finding the largest number. However, to find the third largest number, you need to maintain the state of a list with a capacity of 3, which stores the largest three numbers.

    Each time it is judged whether the number is already in the list;

    If not, judge whether the list is full of 3;

    If it is not full, it will be added directly. If it is full, it will be compared with the smallest number in the list. If it is greater, it will be replaced.


code

class Solution:
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        a=[]
        for x in nums:
            if x not in a:
                if len(a)<3:
                    a.append(x)
                elif x>min(a):
                    a[a.index(min(a))]=x
        if len(a)<3:
            return max(a)
        return min(a)


result


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324700179&siteId=291194637