c++ time: O(n), memory: O(1)


  • 0
    class Solution {
    public:
        void set_first(int x) {
            if (f) set_second(first);
            first = x;
            f = true;
        }
        void set_second(int x) {
            if (s) set_third(second);
            second = x;
            s = true;
        }
        void set_third(int x) {
            third = x;
            t = true;
        }
        int thirdMax(vector<int>& nums) {
            for (int i = 0; i < nums.size(); ++i) {
                int x = nums[i];
                if ((f && first == x) || (s && second == x) || (t && third == x)) continue;
                if (x >= first) set_first(x);
                else if (x >= second) set_second(x);
                else if (x >= third) set_third(x);
            }
            return (t) ? third : first;
        }
    private:
        int first = INT_MIN, second = INT_MIN, third = INT_MIN;
        bool f = false, s = false, t = false;
    };
    

Log in to reply
 

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