|
| 1 | + |
| 2 | +package com.thealgorithms.datastructures.heaps; |
| 3 | + |
| 4 | +import java.util.PriorityQueue; |
| 5 | + |
| 6 | +/** |
| 7 | + * This class provides methods to find the Kth largest or Kth smallest element |
| 8 | + * in an array using heaps. It leverages a min-heap to find the Kth largest element |
| 9 | + * and a max-heap to find the Kth smallest element efficiently. |
| 10 | + * |
| 11 | + * @author Hardvan |
| 12 | + */ |
| 13 | +public final class KthElementFinder { |
| 14 | + private KthElementFinder() { |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * Finds the Kth largest element in the given array. |
| 19 | + * Uses a min-heap of size K to track the largest K elements. |
| 20 | + * |
| 21 | + * Time Complexity: O(n * log(k)), where n is the size of the input array. |
| 22 | + * Space Complexity: O(k), as we maintain a heap of size K. |
| 23 | + * |
| 24 | + * @param nums the input array of integers |
| 25 | + * @param k the desired Kth position (1-indexed, i.e., 1 means the largest element) |
| 26 | + * @return the Kth largest element in the array |
| 27 | + */ |
| 28 | + public static int findKthLargest(int[] nums, int k) { |
| 29 | + PriorityQueue<Integer> minHeap = new PriorityQueue<>(k); |
| 30 | + for (int num : nums) { |
| 31 | + minHeap.offer(num); |
| 32 | + if (minHeap.size() > k) { |
| 33 | + minHeap.poll(); |
| 34 | + } |
| 35 | + } |
| 36 | + return minHeap.peek(); |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Finds the Kth smallest element in the given array. |
| 41 | + * Uses a max-heap of size K to track the smallest K elements. |
| 42 | + * |
| 43 | + * Time Complexity: O(n * log(k)), where n is the size of the input array. |
| 44 | + * Space Complexity: O(k), as we maintain a heap of size K. |
| 45 | + * |
| 46 | + * @param nums the input array of integers |
| 47 | + * @param k the desired Kth position (1-indexed, i.e., 1 means the smallest element) |
| 48 | + * @return the Kth smallest element in the array |
| 49 | + */ |
| 50 | + public static int findKthSmallest(int[] nums, int k) { |
| 51 | + PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a); |
| 52 | + for (int num : nums) { |
| 53 | + maxHeap.offer(num); |
| 54 | + if (maxHeap.size() > k) { |
| 55 | + maxHeap.poll(); |
| 56 | + } |
| 57 | + } |
| 58 | + return maxHeap.peek(); |
| 59 | + } |
| 60 | +} |
0 commit comments