cpp simple solution by 3 loops


  • 0
    P
    class Solution {
    public:
        int thirdMax(vector<int>& nums) {
            if(nums.empty()) return 0;
            int m=nums[0],M=nums[0];
            for(auto n:nums) m=min(n,m),M=max(n,M);
            if(m==M) return M;
            int s=m,t=m;
            for(auto n:nums) if(n!=M) s=max(s,n);
            if(s==m) return M;
            for(auto n:nums) if(n!=M && n!=s) t=max(t,n);
            return t;
        }
    };
    

    The first one, find the maximum, the second one, find the second maximum, and the third one, find the third.


Log in to reply
 

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