Normal Java Solution O(n) time comp


  • 0
    K
    public class Solution {
        public int thirdMax(int[] nums) {
            if (nums == null || nums.length == 0)
                return Integer.MIN_VALUE;
            
            if (nums.length == 1)
                return nums[0];
                
            if (nums.length == 2)
                return nums[0]>=nums[1] ? nums[0] : nums[1];
                
            int m1 = Integer.MIN_VALUE;
            int m2 = Integer.MIN_VALUE;
            int m3 = Integer.MIN_VALUE;
            
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == m1 || nums[i] == m2 || nums[i] == m3)
                    continue;
                
                if (nums[i] > m1) {
                    m3 = m2;
                    m2 = m1;
                    m1 = nums[i];
                } else {
                    if (nums[i] > m2) {
                        m3 = m2;
                    } else {
                        if (nums[i] > m3) {
                            m3 = nums[i];
                        }
                    }
                }
            }
            
            return m3;
        }
    }
    

Log in to reply
 

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