C++ O(n) time & O(1) space solution


  • 0
    K
    class Solution {
    public:
        int thirdMax(vector<int>& nums) {
            long int fst=LONG_MIN,snd=LONG_MIN,trd=LONG_MIN;
            for(int n:nums)
            {
                if(n==fst||n==snd||n==trd) continue;
                if(n>fst)
                {
                    trd=snd;
                    snd=fst;
                    fst=n;
                }
                else if(n>snd)
                {
                    trd=snd;
                    snd=n;
                }
                else if(n>trd)
                    trd=n;
            }
            return trd==LONG_MIN?fst:trd;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.