LeetCode 题解工作台

第三大的数

给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。 示例 1: 输入: [3, 2, 1] 输出: 1 解释: 第三大的数是 1 。 示例 2: 输入: [1, 2] 输出: 2 解释: 第三大的数不存在, 所以返回最大的数 2 。 示例 3: 输入: [2, 2, 3…

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·排序

bolt

答案摘要

我们可以使用三个变量 , , 分别表示数组中的第一大、第二大和第三大的数。初始时,我们将这三个变量都赋值为负无穷大。 然后,我们遍历数组中的每个数,对于每个数,我们将其与 , , 进行比较,根据比较的结果更新这三个变量。具体地,我们遍历数组中的每个数,对于每个数:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

 

示例 1:

输入:[3, 2, 1]
输出:1
解释:第三大的数是 1 。

示例 2:

输入:[1, 2]
输出:2
解释:第三大的数不存在, 所以返回最大的数 2 。

示例 3:

输入:[2, 2, 3, 1]
输出:1
解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。

 

提示:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

 

进阶:你能设计一个时间复杂度 O(n) 的解决方案吗?

lightbulb

解题思路

方法一:一次遍历

我们可以使用三个变量 m1m_1, m2m_2, m3m_3 分别表示数组中的第一大、第二大和第三大的数。初始时,我们将这三个变量都赋值为负无穷大。

然后,我们遍历数组中的每个数,对于每个数,我们将其与 m1m_1, m2m_2, m3m_3 进行比较,根据比较的结果更新这三个变量。具体地,我们遍历数组中的每个数,对于每个数:

  • 如果这个数等于 m1m_1, m2m_2, m3m_3 中的任何一个,我们跳过这个数;
  • 如果这个数大于 m1m_1,我们将 m1m_1, m2m_2, m3m_3 的值更新为 m2m_2, m3m_3, 这个数;
  • 如果这个数大于 m2m_2,我们将 m2m_2, m3m_3 的值更新为 m3m_3, 这个数;
  • 如果这个数大于 m3m_3,我们将 m3m_3 的值更新为这个数。

最后,如果 m3m_3 的值没有被更新,说明数组中不存在第三大的数,那么我们返回 m1m_1,否则我们返回 m3m_3

时间复杂度 O(n)O(n),其中 nn 是数组 nums 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        m1 = m2 = m3 = -inf
        for num in nums:
            if num in [m1, m2, m3]:
                continue
            if num > m1:
                m3, m2, m1 = m2, m1, num
            elif num > m2:
                m3, m2 = m2, num
            elif num > m3:
                m3 = num
        return m3 if m3 != -inf else m1
speed

复杂度分析

指标
时间complexity is O(N) for a single pass or O(N log N) if sorting is used. Space complexity is O(1) for three variables, or O(N) if using a set or heap to store distinct values.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Check for duplicate numbers when considering distinct maxima.

  • question_mark

    Confirm behavior when fewer than three distinct numbers exist.

  • question_mark

    Clarify whether negative and large integer bounds are supported.

warning

常见陷阱

外企场景
  • error

    Failing to ignore duplicates and incorrectly counting repeated numbers as distinct.

  • error

    Sorting the entire array unnecessarily, which increases time complexity.

  • error

    Not handling the case where fewer than three distinct numbers exist.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the k-th distinct maximum number in an array, generalizing the approach for any k.

  • arrow_right_alt

    Return both the third maximum and its index in the original array.

  • arrow_right_alt

    Determine the third minimum number with the same array and duplicate constraints.

help

常见问题

外企场景

第三大的数题解:数组·排序 | LeetCode #414 简单