【easy】Leetcode 414.Third Maximum Number

原题是:

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.

思路是:

利用set,list转换去除list里的重复元素。
然后用List的排序。

代码是:


class Solution:
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        nums = list(set(nums))
        nums.sort()
        if len(nums) >2:
            return nums[-3]
        else :
            return nums[-1]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 经常有人说:你太内向了! 这句话好像在表达一个意思:要外向一点! 其实,内向和外向没有好坏之分,外向的人喜欢在和别...
    币市柳少侠阅读 456评论 0 1
  • 一 褪去了大半个月的热浪,突然一阵晚风拂面,竟有些凉爽。 一早就听妈妈说厦门刮台风还下大雨,但依然很闷热。 我说台...
    水手和狼阅读 123评论 0 0
  • 三年大学到末,仿佛一开始想要的事物都要到了,但拥有后才知道,这并不是结束,而是一个开始。开始什么?开始为自己来个规...
    简单煎蛋减淡阅读 186评论 0 0