Java Solution O(n)


  • 0
    S
    public class Solution {
        public int thirdMax(int[] nums) {
            
            Integer firstMax = null;
            Integer secondMax = null;
            Integer thirdMax = null;
            
            for(int i : nums) {
                if((firstMax != null && i == firstMax) || (secondMax != null && i == secondMax) || (thirdMax != null && i == thirdMax)) {
                    continue;
                }
                
                if(firstMax == null || i > firstMax) {
                    thirdMax = secondMax;
                    secondMax = firstMax;
                    firstMax = i;
                } else if(secondMax == null || i > secondMax) {
                    thirdMax = secondMax;
                    secondMax = i;
                } else if(thirdMax == null || i > thirdMax) {
                    thirdMax = i;
                }
            }
            
            if(thirdMax == null) {
                return firstMax;
            }
            
            return thirdMax;
            
        }
    }
    

Log in to reply
 

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