Add another method to find kth number (#5918)

This commit is contained in:
Taranjeet Singh Kalsi
2024-10-26 16:56:01 +05:30
committed by GitHub
parent 871e4df0d9
commit 95875b0ae4
2 changed files with 30 additions and 0 deletions

View File

@ -1,5 +1,7 @@
package com.thealgorithms.maths;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Random;
/**
@ -62,4 +64,19 @@ public final class FindKthNumber {
array[i] = array[j];
array[j] = temp;
}
public static int findKthMaxUsingHeap(int[] array, int k) {
if (k <= 0 || k > array.length) {
throw new IllegalArgumentException("k must be between 1 and the size of the array");
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); // using max-heap to store numbers.
for (int num : array) {
maxHeap.add(num);
}
while (k > 1) {
maxHeap.poll(); // removing max number from heap
k--;
}
return maxHeap.peek();
}
}