Java solution with explanation


  • 0
    L

    The initialization of the second and third max would be the key as the array may contain -ve integers and MIN_VALUE isn't a good option. Using an AtomicInteger or just an Integer reference is a good option. Just make sure that you don't assign a value to second and third that are already assigned to the max above. Here is the code:

        public int thirdMax(int[] nums) {
            int first=nums[0];
            Integer second = null;
            Integer third = null;
            for(int i=1;i<nums.length;i++) {
                if(nums[i]>first) {
                    third = second;
                    second = first;
                    first = nums[i];
                }
                else if(nums[i]!=first && (second==null || nums[i]>second)) {
                    third = second;
                    second = nums[i];
                }
                else if(nums[i]!=first && nums[i]!=second && (third==null || nums[i]>third)) {
                    third = nums[i];
                }
            }
            
            return third==null?first:third;
        }
    

Log in to reply
 

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