MinHeap of Size 'k'


  • 0
    B
    class Solution {
        public int findKthLargest(int[] nums, int k) {
             if(nums == null || k > nums.length)
                return 0;
            
            if(nums.length == 1)
                return nums[0];
                
           
            PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(k);
            for(int i=0;i<nums.length;i++){
                if(minHeap.size() < k){
                    minHeap.add(nums[i]);
                }else{
                    if(minHeap.peek() < nums[i]){
                        minHeap.poll();
                        minHeap.add(nums[i]);
                    }
                }
            }
            
            return minHeap.peek();
        }
    }
    

Log in to reply
 

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