Untitled
import java.util.PriorityQueue; public class KthLargest { public static int findKthLargest(int[] nums, int k) { // Min-Heap to store the largest K elements PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for (int num : nums) { minHeap.add(num); if (minHeap.size() > k) { minHeap.poll(); // Remove the smallest element } } return minHeap.peek(); // Root of the Min-Heap is the Kth largest element } public static void main(String[] args) { int[] nums = {7, 10, 4, 3, 20, 15}; int k = 3; System.out.println("Kth Largest: " + findKthLargest(nums, k)); // Output: 10 } }
Leave a Comment