Simple java solution using PQ


  • 0
    S
    public class Solution {
        public int thirdMax(int[] nums) {
            
            if(nums == null || nums.length == 0) return -1;
            
            PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
            
            for(int i : nums)
            {
                if(!queue.contains(i)) queue.offer(i);
                if(queue.size() > 3) queue.poll();
            }
            
            if(queue.size() == 3) return queue.peek();
            
            while(queue.size() > 1) queue.poll();
            
            return queue.peek();
        }
    }
    

Log in to reply
 

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