-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_0703KthLargestElementInAStream.java
81 lines (69 loc) · 2.11 KB
/
_0703KthLargestElementInAStream.java
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.heatwave.leetcode.problems;
import java.util.PriorityQueue;
public class _0703KthLargestElementInAStream {
static class KthLargest {
int k;
PriorityQueue<Integer> pq = new PriorityQueue<>();
public KthLargest(int k, int[] nums) {
this.k = k;
for (int num : nums) {
add(num);
}
}
public int add(int val) {
pq.add(val);
if (pq.size() > k) {
pq.remove();
}
return pq.element();
}
}
static class KthLargestBST {
int k;
TreeNode root;
public KthLargestBST(int k, int[] nums) {
this.k = k;
for (int num : nums) {
root = insertIntoBSTWithCnt(root, num);
}
}
public int add(int val) {
root = insertIntoBSTWithCnt(root, val);
return findKth(root, k);
}
private static class TreeNodeWithCnt extends TreeNode {
int cnt;
TreeNodeWithCnt(int val, int cnt) {
this.val = val;
this.cnt = cnt;
}
}
private TreeNode insertIntoBSTWithCnt(TreeNode root, int val) {
if (root == null) {
return new TreeNodeWithCnt(val, 1);
}
((TreeNodeWithCnt) root).cnt++;
if (root.val >= val) {
root.left = insertIntoBSTWithCnt(root.left, val);
return root;
}
root.right = insertIntoBSTWithCnt(root.right, val);
return root;
}
private int findKth(TreeNode root, int k) {
int currentK;
if (root.right == null) {
currentK = 1;
} else {
currentK = ((TreeNodeWithCnt) root.right).cnt + 1;
}
if (k == currentK) {
return root.val;
} else if (k > currentK) {
return findKth(root.left, k - currentK);
} else {
return findKth(root.right, k);
}
}
}
}