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.

找到数组中不重复的第三小的数字(数值相同的元素不重复计算),要求时间复杂度为O(n),还可以只用常数空间,只需要维护三个变量表示最小的数、第二小的数和第三小的数,每次遍历到一个元素,就更新这三个变量。

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        long a=LONG_MIN;
        long b=LONG_MIN;
        long c=LONG_MIN;
        bool exist=false;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]>a)
            {
                c=b;
                b=a;
                a=nums[i];
            }
            else if(nums[i]<a&&nums[i]>b)
            {
                c=b;
                b=nums[i];
            }
            else if(nums[i]<b&&nums[i]>c)
            {
                c=nums[i];
            }
        }
        if(c==LONG_MIN) return a;
        else return c;
    } 
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值