【leetcode】414. Third Maximum Number【E】【85】


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.

Subscribe to see which companies asked this question



找第三大的數,剛開始還想着要不要維護一個大小爲3的最大堆

後來一想,直接set一下,去一下重

然後輸出第三大就行了啊

果然就行了


class Solution(object):
    def thirdMax(self, nums):
        
        nums = set(nums)
        nums = list(nums)
        
        nums.sort(reverse = True)
        #print nums
        
        if len(nums) < 3:
            return max(nums)
        
        return nums[2]


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章