O(n) + O(1) Java solution but used three loops.


  • 0
    Y
    public class Solution {
        public int thirdMax(int[] nums) {
            if (nums.length == 1) {
                return nums[0];
            }
            if (nums.length == 2) {
                return Math.max(nums[0], nums[1]);
            } 
            int firstMax = nums[0];
            for (int num : nums) {
                if (firstMax < num) {
                    firstMax = num;
                }
            }
            int secondMax = Integer.MIN_VALUE;
            for (int num : nums) {
                if (secondMax < num && num < firstMax) {
                    secondMax = num;
                }
            }
            int thirdMax = Integer.MIN_VALUE;
            boolean update = false; // In case Integer.MIN_VALUE is in the array. 
            for (int num : nums) {
                if (thirdMax <= num && num < secondMax) {
                    thirdMax = num;
                    update = true;
                }
            }
            return update? thirdMax : firstMax;
        }
    }
    
    

Log in to reply
 

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