mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
java: add «703. Kth Largest Element in a Stream»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
2e4f1e770b
commit
28379bfe10
1 changed files with 27 additions and 0 deletions
27
java/kth-largest-element-in-a-stream.java
Normal file
27
java/kth-largest-element-in-a-stream.java
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue