Using Long to handle all edge cases O(n) time complexity and O(1) space


  • 0
    S

    //Using Long to handle all edge cases
    //O(n) time complexity and O(1) space

    public class Solution {
        public int thirdMax(int[] nums) {
            long firstMax = Long.MIN_VALUE;
            long secondMax = Long.MIN_VALUE;
            long thirdMax = Long.MIN_VALUE;
            
            for(int num : nums){
                if (num > thirdMax){
                    if (num > secondMax){
                        if (num > firstMax){
                            thirdMax = secondMax;
                            secondMax = firstMax;
                            firstMax = num;
                        }else if (num < firstMax){
                            thirdMax = secondMax;
                            secondMax = num;
                        }
                    }else if (num < secondMax){
                        thirdMax = num;
                    }
                }
            }
            
            return (int)(thirdMax == Long.MIN_VALUE ? firstMax : thirdMax);
        }
    }
    

Log in to reply
 

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