LeetCode 414. Third Maximum Number

本文介绍了一种在O(n)时间复杂度内找到数组中第三大数的算法,通过使用三个整型变量记录并更新最大值,实现了高效查找。若不存在第三大数,则返回最大数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 题目描述
    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.

  • 解题思路
    用三个整型变量来记录,以数组中第一个数字来作为初始值,然后遍历一个一个数字去比较看应该替代三个数字中哪个数字,注意如果比第一个数字大,那么原本第一个数字的值要移动到第二个,原本第二个数字的值要移动到第三个,如果替代的是第二个数字,同样要把原本第二个数字的值移动到第三个,道理很简单。由于我们是用第一个数字作为初始值的,因此在替换数字时还有一个原因就是如果第二个和第三个数字还是初始值,而出现了与初始值不同的数字,那就不要求比原数字大了,直接替换并后移,否则如果第一个数字最大,那即使有第三大数字也不会记录下来。最后要判断三个数字是不是不一样,不一样才返回第三大数字,否则就要返回最大的数字。

  • 代码

public class Solution {
    public int thirdMax(int[] nums) {
        int first = nums[0];
        int second = nums[0];
        int third = nums[0];
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > first) {
                third = second;
                second = first;
                first = nums[i];
            } else if (nums[i] != first && (nums[i] > second || second == first)) {
                third = second;
                second = nums[i];
            } else if ((nums[i] != first && nums[i] != second) && (nums[i] > third || third == second || third == first)) {
                third = nums[i];
            }
        }
        if (first > second && second > third) return third;
        else return first;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值