-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
30 lines (29 loc) · 830 Bytes
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { PriorityQueue } from "./PriorityQueue.ts";
interface KthLargest {
add(val: number): number;
}
function KthLargest(k: number, nums: number[]): KthLargest {
//降序排列
const minheap = PriorityQueue<number>((a, b) => -a + b, nums);
//
// for (const n of nums) {
// minheap.offer(n);
// }
//Array.from(nums).sort((a, b) => -a + b)
function add(val: number): number {
minheap.offer(val);
// minheap.sort((a, b) => -a + b)
while (minheap.length() > k) {
minheap.pop();
}
if (minheap.length()) {
const tail = minheap.tail();
if (typeof tail !== "undefined") {
return tail;
}
}
throw Error("pop empty heap");
}
return { add };
}
export default KthLargest;