C# Solution


  • 0
    M
     public int ThirdMax(int[] nums) {
        if (nums.Length == 1) return nums[0];
        else if (nums.Length == 2) return nums[0] > nums[1] ? nums[0] : nums[1];
        
        int firstMax = int.MinValue; 
        int secondMax = int.MinValue; 
        int thirdMax = int.MinValue; 
        
        bool hasMin = false; 
        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] == int.MinValue)
            {
                hasMin = true; 
                continue; 
            }
            
            if (nums[i] == firstMax || nums[i] == secondMax || nums[i] == thirdMax) continue; 
            
            if (nums[i] > firstMax)
            {
                thirdMax = secondMax; 
                secondMax = firstMax; 
                firstMax = nums[i]; 
            }
            else if (nums[i] > secondMax)
            {
                thirdMax = secondMax; 
                secondMax = nums[i];
            }
            else if (nums[i] > thirdMax) 
            {
                thirdMax = nums[i]; 
            }
        }
        
        if (hasMin == false && (secondMax == int.MinValue || thirdMax == int.MinValue)) return firstMax; 
        if (hasMin == true && secondMax == int.MinValue) return firstMax; 
        if (hasMin == true && secondMax > thirdMax) return thirdMax; 
        else return thirdMax; 
    }

Log in to reply
 

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