My solution without MIN_VALUE


  • 0
    L
    public class Solution {
        public int thirdMax(int[] nums) {
            if(nums.length == 1) return nums[0];
            if(nums.length == 2) 
                return nums[0] > nums[1] ? nums[0] : nums[1];
            
            int firstmax = nums[0];
            int firstmin = nums[0];
            for(int i = 1; i < nums.length; i++) {
                firstmax = Math.max(firstmax, nums[i]);
                firstmin = Math.min(firstmin, nums[i]);
            }
            
            int secondmax = firstmin;
            for(int i = 0; i < nums.length; i++) {
                if(nums[i] < firstmax)
                    secondmax = Math.max(secondmax, nums[i]);
            }
            
            if(secondmax < firstmax) {
                int thirdmax = firstmin;
                for(int i = 0; i < nums.length; i++) {
                    if(nums[i] < secondmax)
                        thirdmax = Math.max(thirdmax, nums[i]);
                }
                if(thirdmax < secondmax) return thirdmax;
            }
            return firstmax;
        }
    }
    

Log in to reply
 

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