C++ solution.


  • 0
    W
    class Solution {
    public:
        int thirdMax(vector<int>& nums) {
           int64_t UNDEF = std::numeric_limits<int64_t>::min();
           int64_t max0 = nums[0];
           int64_t max1 = UNDEF;
           int64_t max2 = UNDEF;
           for (int i = 1, n = nums.size(); i < n; ++i) {
               int x = nums[i];
               if (x == max0 || x == max1)
                   continue;
               if (x > max0) {
                   max2 = max1;
                   max1 = max0;
                   max0 = x;
               }
               else if (x > max1) {
                   max2 = max1;
                   max1 = x;
               }    
               else if (x > max2)
                   max2 = x;
           }
           
           return (max2 != UNDEF) ? max2 : max0;
        }
    };

Log in to reply
 

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