Java easy solution in run time O(n) and space O(1)


  • 0
    T
        public int thirdMax(int[] nums) {
            int len = nums.length;
            Integer max = null;
            Integer secMax = null;
            Integer thirdMax = null;
            for (int num : nums) {
                if (max == null || num > max) {
                    thirdMax = secMax;
                    secMax = max;
                    max = num;
                }
                else if (secMax == null || num > secMax) {
                    if (num == max)
                        continue;
                    thirdMax = secMax;
                    secMax = num;
                }
                else if (thirdMax == null || num > thirdMax) {
                    if (num == secMax)
                        continue;
                    thirdMax = num;
                }
            }
            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.