力扣1172.餐盘栈

力扣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;
      }
  };
相关推荐
I'm a winner1 小时前
第五章:Python 数据结构:列表、元组与字典(一)
开发语言·数据结构·python
过河卒_zh15667661 小时前
9.13AI简报丨哈佛医学院开源AI模型,Genspark推出AI浏览器
人工智能·算法·microsoft·aigc·算法备案·生成合成类算法备案
D.....l1 小时前
冒泡排序与选择排序以及单链表与双链表
数据结构·算法·排序算法
欧阳天风1 小时前
链表运用到响应式中
javascript·数据结构·链表
sinat_286945191 小时前
Case-Based Reasoning用于RAG
人工智能·算法·chatgpt
Athenaand1 小时前
代码随想录算法训练营第50天 | 图论理论基础、深搜理论基础、98. 所有可达路径、广搜理论基础
算法·图论
地平线开发者1 小时前
征程 6 灰度图部署链路介绍
人工智能·算法·自动驾驶·汽车
靠近彗星2 小时前
2.3单链表
数据结构