Skip to content

Commit ef8eea5

Browse files
authored
Create dinner-plate-stacks.cpp
1 parent e4efaa4 commit ef8eea5

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

C++/dinner-plate-stacks.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Time: push: O(logn)
2+
// pop: O(1), amortized
3+
// popAtStack: O(logn)
4+
// Space: O(n * c)
5+
6+
class DinnerPlates {
7+
public:
8+
DinnerPlates(int capacity) : c_(capacity) {
9+
}
10+
11+
void push(int val) {
12+
if (!min_heap_.empty()) {
13+
const auto l = min_heap_.top(); min_heap_.pop();
14+
if (l < stks_.size()) {
15+
stks_[l].emplace_back(val);
16+
return;
17+
}
18+
min_heap_ = {}; // nothing is valid in min heap
19+
}
20+
if (stks_.empty() || stks_.back().size() == c_) {
21+
stks_.emplace_back();
22+
}
23+
stks_.back().emplace_back(val);
24+
}
25+
26+
int pop() {
27+
while (!stks_.empty() && stks_.back().empty()) {
28+
stks_.pop_back();
29+
}
30+
if (stks_.empty()) {
31+
return -1;
32+
}
33+
auto result = stks_.back().back(); stks_.back().pop_back();
34+
return result;
35+
}
36+
37+
int popAtStack(int index) {
38+
if (index >= stks_.size() || stks_[index].empty()) {
39+
return -1;
40+
}
41+
min_heap_.emplace(index);
42+
auto result = stks_[index].back(); stks_[index].pop_back();
43+
return result;
44+
}
45+
46+
private:
47+
vector<vector<int>> stks_;
48+
int c_;
49+
priority_queue<int, vector<int>, greater<int>> min_heap_;
50+
};

0 commit comments

Comments
 (0)