Java Concise Solution


  • 1
    public class Solution {
        public int thirdMax(int[] nums) {
            Integer max = null, mid = null, min = null;
            for (int num : nums) {
                if (max == null || num > max) {
                    min = mid;
                    mid = max;
                    max = num;
                }
                else if ((mid == null || num > mid) && num != max) {
                    min = mid;
                    mid = num;
                }
                else if ((min == null || num > min) && num != max && num != mid) {
                    min = num;
                }
            }
            return min == null ? max : min;
        }
    }
    

  • 0
    C

    Similar

    public class Solution {
        public int thirdMax(int[] nums) {
            Integer[] max = new Integer[3];
            for (int num : nums) {
                if      (max[2] == null || num > max[2]) exchMax(max, num);
                else if (max[1] == null || num > max[1]) exchMed(max, num);
                else if (max[0] == null || num > max[0]) exchMin(max, num);
            }
            return max[0] != null ? max[0] : max[2];
        }
        
        private void exchMax(Integer[] a, int num) {
            a[0] = a[1];
            a[1] = a[2];
            a[2] = num;
        }
        
        private void exchMed(Integer[] a, int num) {
            if (num != a[2]) {
                a[0] = a[1];
                a[1] = num;
            }
        }
        
        private void exchMin(Integer[] a, int num) {
            if (num != a[2] && num != a[1])
                a[0] = num;
        }
    }

Log in to reply
 

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