LeetCode 414——第三大的数

一、题目介绍

给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。

示例 1:

输入: [3, 2, 1]

输出: 1

解释: 第三大的数是 1.
示例 2:

输入: [1, 2]

输出: 2

解释: 第三大的数不存在, 所以返回最大的数 2 .
示例 3:

输入: [2, 2, 3, 1]

输出: 1

解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。
存在两个值为2的数,它们都排第二。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/third-maximum-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、解题分析

本题需要注意一下当数组中的元素为INT_MIN的情况,实现思路比较简单,直接看代码即可。

三、解题代码

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        int first = INT_MIN, second = INT_MIN, third = INT_MIN;
        bool flag = false;
        for(int i = 0; i < nums.size(); ++i)
        {
            if((nums[i] == first || nums[i] == second) && nums[i] != INT_MIN) //去重 需排除元素为INT_MIN的情况
                continue;
            else if(nums[i] > first)
            {
                third = second;
                second = first;
                first = nums[i];
            }
            else if(nums[i] > second)
            {
                third = second;
                second = nums[i];
            }
            else if(nums[i] > third)
            {
                third = nums[i];
            }
            else 
                flag = true;
        }
        if(second != third && (third != INT_MIN || flag))
            return third;
        return first;
    }
};

四、解题结果

发布了139 篇原创文章 · 获赞 122 · 访问量 4741

猜你喜欢

转载自blog.csdn.net/qq_39661206/article/details/103429674