Skip to content

Commit 5f7bd46

Browse files
committed
Add step5
1 parent e1caaf5 commit 5f7bd46

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

703/step5.cpp

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
class KthLargest {
2+
public:
3+
KthLargest(int k, vector<int>& nums) : capacity(k) {
4+
for (int num: nums) {
5+
if (preserved_nums.size() < capacity) {
6+
push(num);
7+
continue;
8+
}
9+
if (num < preserved_nums.front()) {
10+
continue;
11+
}
12+
push(num);
13+
if (preserved_nums.size() > capacity) {
14+
pop();
15+
}
16+
}
17+
}
18+
19+
int add(int val) {
20+
if (preserved_nums.empty()) {
21+
preserved_nums.push_back(val);
22+
return val;
23+
}
24+
if (preserved_nums.size() == capacity && preserved_nums.front() > val) {
25+
return preserved_nums.front();
26+
}
27+
push(val);
28+
if (preserved_nums.size() > capacity) {
29+
pop();
30+
}
31+
return preserved_nums.front();
32+
}
33+
private:
34+
int capacity;
35+
vector<int> preserved_nums;
36+
37+
int parent_index(int index) {
38+
return (index - 1) / 2;
39+
}
40+
41+
void sift_up_from_last() {
42+
int index = preserved_nums.size() - 1;
43+
while (index > 0) {
44+
int parent_index_ = parent_index(index);
45+
if (preserved_nums[index] >= preserved_nums[parent_index_]) {
46+
break;
47+
}
48+
swap(preserved_nums[index], preserved_nums[parent_index_]);
49+
index = parent_index_;
50+
}
51+
}
52+
53+
int left_child_index(int index) {
54+
return index * 2 + 1;
55+
}
56+
57+
int right_child_index(int index) {
58+
return index * 2 + 2;
59+
}
60+
61+
int min_child_index(int index) {
62+
int left = left_child_index(index);
63+
int right = right_child_index(index);
64+
if (right >= preserved_nums.size()) {
65+
return left;
66+
}
67+
if (preserved_nums[left] <= preserved_nums[right]) {
68+
return left;
69+
}
70+
return right;
71+
}
72+
73+
bool has_child(int index) {
74+
return left_child_index(index) < preserved_nums.size();
75+
}
76+
77+
void sift_down_from_root() {
78+
int index = 0;
79+
while (has_child(index)) {
80+
int min_child_index_ = min_child_index(index);
81+
if (preserved_nums[min_child_index_] >= preserved_nums[index]) {
82+
break;
83+
}
84+
swap(preserved_nums[min_child_index_], preserved_nums[index]);
85+
index = min_child_index_;
86+
}
87+
}
88+
89+
void push(int num) {
90+
preserved_nums.push_back(num);
91+
sift_up_from_last();
92+
}
93+
94+
void pop() {
95+
swap(preserved_nums.front(), preserved_nums.back());
96+
preserved_nums.pop_back();
97+
sift_down_from_root();
98+
}
99+
};

0 commit comments

Comments
 (0)