Third Maximum Number解题报告

Description:

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:

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.

Link:

https://leetcode.com/problems/third-maximum-number/#/description

解题方法:

用三个数分别储存第一、第二、第三大的数,当出现等于这三个数的情况,不进行更新。

Tips:

为了防止数组中有INT_MIN,用long来储存,这样初始化为比INT_MIN还小的数,最后就可以知道第三大的数有没有更新。

Time Complexity:

O(N)

完整代码:

int thirdMax(vector<int>& nums) 
    {
        long max1 = (long)INT_MIN - 1, max2 = (long)INT_MIN - 1, max3 = (long)INT_MIN - 1;
        for(int i: nums)
        {
            if(i == max1 || i == max2 || i == max3)
                continue;
            if(i > max1)
            {
                max3 = max2;
                max2 = max1;
                max1 = i;
            }
            else
                if(i > max2)
                {
                    max3 = max2;
                    max2 = i;
                }
                else
                    if(i > max3)
                        max3 = i;      
        }
        return max3 == (long)INT_MIN - 1 ? max1 : max3;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,354评论 0 33
  • 那天阳光很好,它是第一朵盛开的花,我曾骄傲地告诉所有人,看呐,我的花开了,开的那么娇艳。 前天中午到家,看到它掉在...
    泽熙_____阅读 3,712评论 0 1