1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/java/kth-largest-element-in-a-stream.java
Matej Focko 28379bfe10
java: add «703. Kth Largest Element in a Stream»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-08-12 11:50:04 +02:00

27 lines
447 B
Java

import java.util.PriorityQueue;
class KthLargest {
int k;
private PriorityQueue<Integer> heap;
public KthLargest(int k, int[] nums) {
this.k = k;
heap = new PriorityQueue<>(k + 1);
for (var num : nums) {
add(num);
}
}
public int add(int val) {
if (heap.size() < k || heap.peek() < val) {
heap.add(val);
if (heap.size() > k) {
heap.remove();
}
}
return heap.peek();
}
}