O(n) AC Java solution, covered new edge case;


  • 0
    B
    public class Solution {
        public int thirdMax(int[] nums) {
            long max, mid, small;
            
            //In case input array contains Integer.MIN_VALUE; initialize three number as long type;
            max = mid = small = Long.MIN_VALUE;
            int count = 0;
            
            for (int x : nums) {
                if (x == max || x == mid || x == small) continue;
                
                if (x > max) {
                    small = mid;
                    mid = max;
                    max = x;
                    
                    count ++;
                } else if (x > mid) {
                    small = mid;
                    mid = x;
                    
                    count ++;
                } else if (x > small) {
                    small = x;
                    
                    count ++;
                }
            }
            
            return (int)((count >= 3) ? small : max);
        }
    }
    

Log in to reply
 

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