【数组】力扣414:第三大的数

给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。
示例1

输入:[1, 2]
输出:2

示例2

输入:[2, 2, 3, 1]
输出:1

可以用到的函数
set() 数列去重
max() 数列最大值
sort() 对给定区间所有元素进行排序,默认为升序
sorted() 降序

我的解答 - 一次遍历

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        # num为数组nums中的数
        # set()函数去重。如果数组的数小于3个,直接返回最大的数
        if len(set(nums)) < 3:
            return max(nums)
        # 用三个变量来维护数组中的最大值、次大值和第三大值,并初始化为比第三大的数更小的数,比如无穷小
        a, b, c = float('-inf'), float('-inf'), float('-inf')
        for num in nums:
            if num > a:
                a, b, c = num, a, b
            elif a > num >b:
                b, c = num, b
            elif b > num >c:
                c = num
        return c

如果开始不判断数组的非重复数,返回的时候可以写为

return a if c == float('-inf') else c

不依赖元素范围的做法是,将 a、b 和 c 初始化为空指针或空对象None,视作「无穷小」,并在比较大小前先判断是否为空指针或空对象。遍历结束后,若 c 为空,则说明第三大的数不存在,返回 a,否则返回 c。

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        a, b, c = None, None, None
        for num in nums:
            if a is None or num > a:
                a, b, c = num, a, b
            elif a > num and (b is None or num > b):
                b, c = num, b
            elif b is not None and b > num and (c is None or num > c):
                c = num
        return a if c is None else c

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/third-maximum-number/solution/di-san-da-de-shu-by-leetcode-solution-h3sp/

排序

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        nums.sort(reverse=True) # 用了reverse,从大到小排列
        diff = 1
        for i in range(1, len(nums)):
            if nums[i] != nums[i - 1]:
                diff += 1
                if diff == 3:  # 此时 nums[i] 就是第三大的数
                    return nums[i]
        return nums[0]

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/third-maximum-number/solution/di-san-da-de-shu-by-leetcode-solution-h3sp/

时间复杂度:O(nlogn),其中 n 是数组 nums 的长度。排序需要O(nlogn) 的时间。
空间复杂度:O(logn)。排序需要的栈空间为O(logn)。

最简便解题法:

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
	# 降序排列
        return sorted(set(nums))[-3]  if len(set(nums)) >= 3 else max(nums)

作者:Jam007
链接:https://leetcode-cn.com/problems/third-maximum-number/solution/yi-xing-dai-ma-si-lu-jian-dan-xing-neng-hj1fb/
posted @   Vonos  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示