find the third largest number

Given a non-empty array, return the third largest number in the array . If not present, returns the largest number in the array.

Example 1:

Input: [3, 2, 1]
Output: 1
Explanation: The third largest number is 1.

Example 2:

Input: [1, 2]
Output: 2
Explanation: The third largest number does not exist, so return the largest number 2.

Example 3:

Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the requirement to return the third largest number refers to the third largest number among all different numbers.
In this example, there are two numbers with value 2, and they both come second. The third largest number among all the different numbers is 1 .

Source: LeetCode
Link: https://leetcode.cn/problems/third-maximum-number

Problem-solving ideas:

First judge whether the number of sets is greater than or equal to 3, not equal to returning max directly, if the condition is satisfied, the list is reversely sorted, and the third element is taken.

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(set(nums))<=2:
            return max(nums)
        a=list(set(nums))
        a.sort(reverse=True)
        return a[2]

Guess you like

Origin blog.csdn.net/Tinyfacture/article/details/131938617
Recommended