C++ Three for-loops


  • 0
    int thirdMax(vector<int>& nums) {
        int max1 = INT_MIN;
        int max2 = INT_MIN;
        int max3 = INT_MIN;
        bool hasIntMin = false;
        
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] > max1) {
                max1 = nums[i];
            }
            
            if(nums[i] == INT_MIN) hasIntMin = true;
        }
        
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] > max2 && nums[i] != max1) {
                max2 = nums[i];
            }
        }
        
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] > max3 && nums[i] != max1 && nums[i] != max2) {
                max3 = nums[i];
            }
        }
        
        if(!hasIntMin){
            return max3 == INT_MIN ? max1 : max3;
        }else{
            return max3 == max2 ? max1 : max3;
        }
        
    }
    

Log in to reply
 

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