Easy, C++ solution using pointers, O(n) time, O(1) space


  • 0
    N
    class Solution {
    public:
        int thirdMax(vector<int>& nums) {
            int *max1, *max2, *max3;
            max1 = &nums[0];
            max2 = nullptr;
            max3 = nullptr;
            for(int i = 1; i < nums.size(); i++){
                if(nums[i]>*max1){
                    max3 = max2;
                    max2 = max1;
                    max1 = &nums[i];
                }
                else if(nums[i]!=*max1){
                    if(max2 == nullptr)
                        max2 = &nums[i];
                    else if(nums[i]>*max2){
                        max3 = max2;
                        max2 = &nums[i];
                    }
                    else if(nums[i]!=*max2){
                        if(max3 == nullptr)
                            max3 = &nums[i];
                        else if(nums[i] > *max3)
                            max3 = &nums[i];
                    }
                }
            }
            if(max3==nullptr)
                return *max1;
            return *max3;
        }
    };
    

Log in to reply
 

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