Java clear solution with O(n) time and O(1) space


  • 0
    A
    public int thirdMax(int[] nums) {
        int max = Integer.MIN_VALUE, secMax = Integer.MIN_VALUE, thdMax = Integer.MIN_VALUE;
        boolean existMinInt = false;
        int count = 0;
        for (int num : nums) {
            if (!existMinInt && num == Integer.MIN_VALUE) {
                existMinInt = true;
                count++;
            }
            if (num > max) {
                thdMax = secMax;
                secMax = max;
                max = num;
                count++;
            } else if (num < max && num > secMax) {
                thdMax = secMax;
                secMax = num;
                count++;
            } else if (num < secMax && num >= thdMax) {
                thdMax = num;
                count++;
            }
        }
        return count > 2 ? thdMax : max;
    }

Log in to reply
 

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