Untitled
unknown
plain_text
23 days ago
811 B
1
Indexable
import java.util.PriorityQueue; import java.util.Collections; public class KthSmallest { public static int findKthSmallest(int[] nums, int k) { // Max-Heap to store the smallest K elements PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); for (int num : nums) { maxHeap.add(num); if (maxHeap.size() > k) { maxHeap.poll(); // Remove the largest element } } return maxHeap.peek(); // Root of the Max-Heap is the Kth smallest element } public static void main(String[] args) { int[] nums = {7, 10, 4, 3, 20, 15}; int k = 3; System.out.println("Kth Smallest: " + findKthSmallest(nums, k)); // Output: 7 } }
Editor is loading...
Leave a Comment