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

解題方法:

用三個數(shù)分別儲存第一、第二、第三大的數(shù),當(dāng)出現(xiàn)等于這三個數(shù)的情況,不進(jìn)行更新。

Tips:

為了防止數(shù)組中有INT_MIN,用long來儲存,這樣初始化為比INT_MIN還小的數(shù),最后就可以知道第三大的數(shù)有沒有更新。

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;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,922評論 0 33
  • 那天陽光很好,它是第一朵盛開的花,我曾驕傲地告訴所有人,看吶,我的花開了,開的那么嬌艷。 前天中午到家,看到它掉在...
    澤熙_____閱讀 698評論 0 1

友情鏈接更多精彩內(nèi)容