Without only priorityqueue


  • 0
    C

    Re: Java PriorityQueue O(n) + O(1)

    public int thirdMax(int[] nums) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for(int num: nums) {
            if(!pq.contains(num)) pq.add(num);
            if(pq.size() > 3) pq.poll();
        }
        if(pq.size() == 3) return pq.peek();
        if(pq.size() < 3) {
            while(pq.size() > 1) pq.poll();
        }
        return pq.peek();
    }

Log in to reply
 

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