Java 7 lines simple solution using PriorityQueue


  • 1
        public int thirdMax(int[] nums) {
            PriorityQueue<Integer> pq = new PriorityQueue<>();
            for (int i : nums) {
                if (!pq.contains(i)) pq.offer(i);
                while (pq.size() > 3) pq.poll();
            }
            if (pq.size() == 2) return Math.max(pq.poll(), pq.poll());
            return pq.poll();
        }
    

Log in to reply
 

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