mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 17:29:31 +08:00
Add another method to find kth number (#5918)
This commit is contained in:

committed by
GitHub

parent
871e4df0d9
commit
95875b0ae4
@ -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();
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user