LeetCode 215: Kth Largest Element in an Array

Problem Description

Explanation

To find the kth largest element in an array without sorting, we can use a min-heap data structure. We will maintain a heap of size k, where the top element of the heap will be the kth largest element seen so far. We iterate through the array and add each element to the heap. If the size of the heap exceeds k, we remove the minimum element from the heap. At the end of the iteration, the top element of the heap will be the kth largest element in the array.

  • Time complexity: O(n * log k) where n is the number of elements in the array
  • Space complexity: O(k)

Solutions

import java.util.PriorityQueue;

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        
        for (int num : nums) {
            minHeap.add(num);
            if (minHeap.size() > k) {
                minHeap.poll();
            }
        }
        
        return minHeap.peek();
    }
}

Loading editor...