File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
(#703)KthLargestElementinaStream Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ class KthLargest {
2
+ private int k;
3
+ private TreeNode root;
4
+
5
+ public KthLargest(int k, int[] nums) {
6
+ this.k = k;
7
+ for(int i : nums)
8
+ root = buildTree(root, i);
9
+ }
10
+
11
+
12
+ public int add(int val) {
13
+ root = buildTree(root, val);
14
+ return findK();
15
+ }
16
+
17
+ private int findK(){
18
+ TreeNode node = root;
19
+ int count = k;
20
+ while(count > 0){
21
+ int pos = 1 + (node.right == null ? 0 : node.right.count);
22
+ if(pos == count) break;
23
+ if(pos > count)
24
+ node = node.right;
25
+ else {
26
+ node = node.left;
27
+ count -= pos;
28
+ }
29
+ }
30
+ return node.val;
31
+ }
32
+
33
+ private TreeNode buildTree(TreeNode root, int num){
34
+ if(root == null){
35
+ root = new TreeNode(num);
36
+ return root;
37
+ }
38
+ root.count++;
39
+ if(num > root.val)
40
+ root.right = buildTree(root.right, num);
41
+ else root.left = buildTree(root.left, num);
42
+ return root;
43
+ }
44
+ class TreeNode{
45
+ int val;
46
+ int count = 1;
47
+ TreeNode left, right;
48
+
49
+ public TreeNode(int val){
50
+ this.val = val;
51
+ }
52
+ }
53
+ }
You can’t perform that action at this time.
0 commit comments