My long, complicated, not easy to read, c++ solution, thank goodness it's accepted.


  • 0
    Y

    class Solution {
    public:
    int thirdMax(vector<int>& nums) {
    int s = nums.size();
    if(s==1){// 1 number
    return nums[0];
    }
    else if(s==2)//2 numbers
    return nums[0]>nums[1] ? nums[0]:nums[1];
    else{ //at least 3 numbers
    int max1, max2, max3, i, c; // c refers to challenger
    //initialize max1,max2,max3
    max1 = max2 = max3 = nums[0];
    // afterward
    i=1;
    while(i<s){
    c = nums[i];
    if(max1 == max2 && max2 == max3){ // second and third max not found currently
    if(c>max1)
    max1=c;
    else if(c<max1)
    max2=max3=c;
    }else if(max2 == max3){ // the third max not found currently
    if(c>max1){
    max2=max1; max1=c;
    }else if(c<max1 && c>max2){
    max2=c;
    }else if(c<max2){
    max3=c;
    }
    }else{ //
    if(c>max1){
    max3 = max2; max2 = max1; max1 =c;
    }else if(c<max1 && c>max2){
    max3 = max2; max2 = c;
    }else if(c<max2 && c>max3){
    max3 = c;
    }
    }
    i++;
    }//while
    if(max2 == max3){
    return max1;
    }else
    return max3;
    }//else: at least 3 numbers
    }//thirdMax
    };// class soluthion


Log in to reply
 

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