lurenaa的博客

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
class KthLargest {
public:
struct Node {
int val;
Node* left;
Node* right;
int count;
Node(int val) : val(val), count(1),left(nullptr), right(nullptr) {}
};
struct Tree {
void insert(int val) {
root = insert(val, root);
}
int count(Node* nd) {
if(nd)
return nd->count;
else return 0;
}
Node* insert(int val, Node* nd) {
if(!nd)
return new Node(val);
if(val > nd->val)
nd->right = insert(val, nd->right);
else if (val <= nd->val)
nd->left = insert(val, nd->left);
nd->count = 1 + count(nd->left) + count(nd->right);
return nd;
}
Node* findKth(int k, Node* nd) {
if(!nd)
return nullptr;
int lef = count(nd->left);
if(k == lef)
return nd;
else if (lef > k)
return findKth(k, nd->left);
else
return findKth(k - lef - 1,nd->right);
}
int findKth(int k) {
return findKth(k, root)->val;
}
Node* root = nullptr;
};
Tree tree;
int n;
int k ;
KthLargest(int k, vector<int>& nums) {
for(auto x: nums)
tree.insert(x);
n = nums.size();
this->k = k;
}

int add(int val) {
++n;
tree.insert(val);
// cout << n << endl;
// cout << tree.root->count << endl;
return tree.findKth(n - k );
}
};

Accepted

10/10 cases passed (512 ms)

Your runtime beats 9.05 % of cpp submissions

Your memory usage beats 5.03 % of cpp submissions (34.1 MB)