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


  • 0
    C
    public int thirdMax(int[] nums) {
            int len = nums.length;
            if (len == 1) return nums[0];
            if (len == 2) return Math.max(nums[0], nums[1]);
            long max = Long.MIN_VALUE, secMax = Long.MIN_VALUE, thirdMax = Long.MIN_VALUE;
            for (int num : nums) {
                if (num > max) {
                    if (max > secMax) {
                        if (secMax > thirdMax) {
                            thirdMax = secMax;
                        }
                        secMax = max;
                    }
                    max = num;
                }
                else if (num != max && num > secMax) {
                    if (secMax > thirdMax) {
                            thirdMax = secMax;
                        }
                    secMax = num;
                }
                else if (num != max && num != secMax && num > thirdMax) thirdMax = num;
            }
            return thirdMax == Long.MIN_VALUE ? (int)max : (int)thirdMax;
    }

Log in to reply
 

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