Java minheap solution


  • 0
    D
    public class Solution {
        public int thirdMax(int[] nums) {
            if (nums == null || nums.length == 0) {
                return 0;
            }
            int largest = Integer.MIN_VALUE;
            Set<Integer> set = new HashSet<>();
            for (int num : nums) {
                set.add(num);
                largest = Math.max(largest, num);
            }
            Queue<Integer> minheap = new PriorityQueue<>();
            for (int num : set) {
                if (minheap.size() < 3) {
                    minheap.offer(num);
                } else if (num > minheap.peek()) {
                    minheap.poll();
                    minheap.offer(num);
                }
            }
            return minheap.size() == 3 ? minheap.peek() : largest;
        }
    }
    

Log in to reply
 

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