Simple Java Solution using TreeMap O(n)


  • 0
    M
    public class Solution {
        public int thirdMax(int[] nums) {
            if(nums.length == 0)
                return 0;
            
            TreeSet<Integer> set = new TreeSet<>();
            
            for(int num : nums)
            {
                set.add(num);
                if(set.size() > 3)
                    set.pollFirst();
            }
            
            if(set.size() < 3)
                return set.pollLast();
            else
                return set.pollFirst();
        }
    }
    

Log in to reply
 

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