Accepted simple Java solution without using a counter


  • 0
    S
    public static int thirdMax(int[] nums) {
        if (nums == null) return 0;
        Integer max = null, mid = null, min = null;
    
        for (int i = 0; i < nums.length; i++) {
            int x = nums[i];
            if (max != null && x == max || mid != null && x == mid || min != null && x == min) continue;
    
            if (max == null || x > max) {
                min = mid;
                mid = max;
                max = x;
    
            } else if (mid == null || x > mid) {
                min = mid;
                mid = x;
    
            } else if (min == null || x > min) {
                min = x;
            }
        }
        return min == null ? max : min;
    }
    

Log in to reply
 

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