Java O(n) time and O(1) space


  • 0
    R

    public class Solution {
    public int thirdMax(int[] nums) {

        Integer max = null;
        Integer secMax = null;
        Integer thirdMax = null;
        
        for (int i : nums) {
            if (max == null || i > max) {
                thirdMax = secMax;
                secMax = max;
                max = i;
            } else if (i < max) {
                if (secMax == null || i > secMax) {
                    thirdMax = secMax;
                    secMax = i;
                } else if (i < secMax) {
                    if (thirdMax == null) {
                        thirdMax = i;
                    } else {
                        thirdMax = Math.max(thirdMax, i);
                    }
                }
            }
        }
        
        if (thirdMax == null) {
            return max;
        }
        
        return thirdMax;
    }
    

    }


Log in to reply
 

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