Short O(n) time O(1) space treeset solution


  • 0
    C
    public int thirdMax(int[] nums) {
            TreeSet<Integer> max3 = new TreeSet<>();
            int idx = 0;
            while(max3.size() < 3 && idx < nums.length) max3.add(nums[idx++]);
            if(max3.size() < 3) return max3.last();
            for(int i=3;i<nums.length;i++){
                if(nums[i] > max3.first()){
                    max3.add(nums[i]);
                    if(max3.size() > 3) max3.pollFirst();
                }
            }
            return max3.first();
        }
    

Log in to reply
 

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