JAVA O(n) Solution


  • 0
    Y
    public class Solution {
        public int thirdMax(int[] nums) {
            int first = Integer.MIN_VALUE;
            int second = first;
            int third = second;
            int count = 0;
            int minCount = 0;
            for(int i=0; i<nums.length; i++){
                if((nums[i] == first || nums[i] == second || nums[i] == third) && nums[i] != Integer.MIN_VALUE || nums[i] == Integer.MIN_VALUE && minCount == 1){
                    continue;
                }
                if(nums[i] == Integer.MIN_VALUE)
                    minCount++;
                if(nums[i] > first){
                    third = second;
                    second = first;
                    first = nums[i];
                }else if(nums[i] > second){
                    third = second;
                    second = nums[i];
                }else if(nums[i] > third){
                    third = nums[i];
                }
                count++;
            }
            if(count < 3)
                return first;
            return third;
        }
    }

Log in to reply
 

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