LeetCode 414. 第三大的数

题目描述

414. 第三大的数

思路分析

解法一:维护前三大值(推荐)

核心思路

  • 维护三个变量保存不同的最大值。
  • 遍历数组时跳过重复值,依次更新第一、第二、第三大。
  • 若第三大不存在,返回最大值。


复杂度分析

  • 时间复杂度:O(n),其中 n 表示数组长度。
  • 空间复杂度:O(1),仅使用常数额外空间。
class Solution {
    public int thirdMax(int[] nums) {
        long first = Long.MIN_VALUE;
        long second = Long.MIN_VALUE;
        long third = Long.MIN_VALUE;

        for (int num : nums) {
            if (num == first || num == second || num == third) {
                continue;
            }
            if (num > first) {
                third = second;
                second = first;
                first = num;
            } else if (num > second) {
                third = second;
                second = num;
            } else if (num > third) {
                third = num;
            }
        }

        return third == Long.MIN_VALUE ? (int) first : (int) third;
    }
}
import "math"

func thirdMax(nums []int) int {
	first := int64(math.MinInt64)
	second := int64(math.MinInt64)
	third := int64(math.MinInt64)

	for _, v := range nums {
		num := int64(v)
		if num == first || num == second || num == third {
			continue
		}
		if num > first {
			third = second
			second = first
			first = num
		} else if num > second {
			third = second
			second = num
		} else if num > third {
			third = num
		}
	}

	if third == int64(math.MinInt64) {
		return int(first)
	}
	return int(third)
}

相似题目

题目 难度 考察点
215. 数组中的第K个最大元素 中等 选择
703. 数据流中的第 K 大元素 简单
347. 前 K 个高频元素 中等
973. 最接近原点的 K 个点 中等
692. 前K个高频单词 中等
本文作者:
本文链接: https://hgnulb.github.io/blog/2026/71639474
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!