Skip to content

Commit 0be8528

Browse files
committed
AC, why array is ok but vector is error?
1 parent 4ebd4a5 commit 0be8528

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

P703.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include "header.h"
2+
#include <bits/c++config.h>
3+
#include <cstddef>
4+
#include <vector>
5+
6+
class KthLargest {
7+
public:
8+
int knums[20000], nk;
9+
int K;
10+
KthLargest(int k, vector<int>& nums) {
11+
nk = 0;
12+
K = k;
13+
if (nums.empty()) return;
14+
sort(nums.begin(), nums.end(), greater<int>());
15+
int n = min<int>(k, nums.size());
16+
for (int i=0; i<n ; i++)
17+
knums[nk++] = nums[i];
18+
// print(knums);
19+
}
20+
21+
int add(int val) {
22+
if (nk >= K && val<=knums[nk-1])
23+
return knums[nk-1];
24+
if (nk <K)
25+
knums[nk++] = val;
26+
int i=nk-1;
27+
while (i>0 && val>knums[i-1]) {
28+
knums[i] = knums[i-1];
29+
i--;
30+
}
31+
knums[i] = val;
32+
// print(knums);
33+
return knums[K-1];
34+
}
35+
36+
};
37+
38+
/**
39+
* Your KthLargest object will be instantiated and called as such:
40+
* KthLargest* obj = new KthLargest(k, nums);
41+
* int param_1 = obj->add(val);
42+
*/
43+
44+
int main() {
45+
int k = 1;
46+
vector<int> nums = {};
47+
KthLargest *obj = new KthLargest(k, nums);
48+
cout << obj->add(-3) << endl;
49+
cout << obj->add(-2) << endl;
50+
cout << obj->add(-4) << endl;
51+
cout << obj->add(0) << endl;
52+
cout << obj->add(4) << endl;
53+
return 0;
54+
}

0 commit comments

Comments
 (0)