力扣1172.餐盘栈
-
优先队列 + 栈
- 优先队列维护所有非满栈下标
cpp
class DinnerPlates {
int k = 0;
vector<stack<int>> stacks;
priority_queue<int,vector<int>,greater<>> idx;
public:
DinnerPlates(int capacity) {
k = capacity;
}
void push(int val) {
//处理所有越界下标
if(!idx.empty() && idx.top() >= stacks.size())
while(!idx.empty()) idx.pop();
if(idx.empty())
{
stack<int> st;
st.push(val);
stacks.emplace_back(st);
if(k > 1)
idx.push(stacks.size() - 1);
}
else
{
auto &st = stacks[idx.top()];
st.push(val);
//满了就弹出队列
if(st.size() == k)
idx.pop();
}
}
int pop() {
//相当于删最后一个
return popAtStack(stacks.size() - 1);
}
int popAtStack(int index) {
//不合法操作
if (index < 0 || index >= stacks.size() || stacks[index].empty())
return -1;
auto &st = stacks[index];
//如果是满栈,删了以后必定不满,如果是非满栈,则一定已经在队列里了
if(st.size() == k)
idx.push(index);
int val = st.top();
st.pop();
//处理尾部空栈
while(!stacks.empty() && stacks.back().empty())
stacks.pop_back();
return val;
}
};