simplest C++ version time O(n), only five registers required


  • 0
    Y

    class Solution {
    public:
    int thirdMax(vector<int>& nums) {
    int firstMax = -2147483648;
    int secondMax = -2147483648;
    int thirdMax = -2147483648;
    bool third_touched = false;
    for(int i = 0; i < nums.size(); ++i){
    if(nums[i] > firstMax){

                thirdMax = secondMax;
                secondMax = firstMax;
                firstMax = nums[i];
            }
            else if(nums[i] > secondMax){
                if(nums[i] != firstMax){
                    thirdMax = secondMax;
                    secondMax = nums[i];
                    
                }
            }
            else if(nums[i] > thirdMax){
                if(nums[i] != secondMax){
                    thirdMax = nums[i];
                    third_touched = true;
                }
            }
            else if(nums[i] == thirdMax){
                if(!third_touched)
                    third_touched = true;
            }
        }
        if(thirdMax == -2147483648){
            if(firstMax == -2147483648)
                return thirdMax;
            else if(secondMax == -2147483648)
                return firstMax;
            else if(third_touched)
                return thirdMax;
            else
                return firstMax;
        }
        else
            return thirdMax;
    }
    

    };


Log in to reply
 

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