[leetcode]: 414. Third Maximum Number

1.题目

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

第三大的数是1

Example 2:
Input: [1, 2]
Output: 2

第三大的数不存在,所以返回最大值2

Example 3:
Input: [2, 2, 3, 1]
Output: 1

注意第三大的数不包括重复的数,所以第三大的数是1

2.分析

大致两种思路:
方法1: 使整个数组的元素有序,返回第三大的数。注意去重。
实现可以借助数据结构,例如c++的set
方法2:维护一个长度为k=3的数据结构,其中存放了当前遍历到的元素中前k=3大的数。这种方法可以扩展到当数组长度很大,k也很大的情况。
如果k比较大,可以考虑大根堆
此题中k=3,可以直接用三个变量分别存放前3大的数。

3.代码

方法1:

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        set<int> seq(nums.begin(), nums.end());
        set<int>::reverse_iterator it = seq.rbegin();
        if (seq.size() < 3)
            return *it;
        else {
            ++it;
            ++it;
            return *it;
        }
    }
};

方法2:
注意类型要用long long

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        long long max_1 = LLONG_MIN;
        long long max_2 = LLONG_MIN;
        long long max_3 = LLONG_MIN;
        for (auto n : nums) {
            if (n == max_3 || n == max_2 || n == max_1)
                continue;
            else if(n > max_1) {
                max_3 = max_2;
                max_2 = max_1;
                max_1 = n;
            }
            else if (n > max_2) {
                max_3 = max_2;
                max_2 = n;
            }
            else if (n > max_3)
                max_3 = n;
        }
        return max_3 == LLONG_MIN ? max_1 : max_3;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值