O(n) Time and space without C++ stl


  • 0
    G
    class Solution {
    public:
        int thirdMax(vector<int>& nums) {
            int first=nums[0];
            int second=INT_MIN;
            int third=INT_MIN;
            bool flag=false;
             if(nums.size()<3)
             return max(nums[0],nums[1]);
            for(int i=1;i<nums.size();i++)
            {
                if(nums[i]>first)
                {
                    third=second;
                    second=first;
                    first=nums[i];
                }
                else if(nums[i]>second&&nums[i]<first)
                {
                    third=second;
                    second=nums[i];
                }
                else if(nums[i]>third&&nums[i]<second)
                {
                    third=nums[i];
                }
            }
            for(int i=0;i<nums.size();i++)
            if(third==nums[i]&&third!=second)
            {
               return third;
            }
       
            return first;
           
        }
    };
    

Log in to reply
 

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