力扣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;
      }
  };
相关推荐
এ᭄画画的北北1 小时前
力扣-35.搜索插入位置
数据结构·算法·leetcode
cylat1 小时前
Day23 pipeline管道
人工智能·python·算法·机器学习
lucky_jiexia2 小时前
leetcode刷题经验
算法·leetcode·哈希算法
蓝澈11212 小时前
数据结构之常用排序算法(冒泡、选择等)
数据结构·算法·排序算法
有梦想的骇客8 小时前
书籍将正方形矩阵顺时针转动90°(8)0605
线性代数·算法·矩阵
有梦想的骇客8 小时前
书籍“之“字形打印矩阵(8)0609
java·算法·矩阵
Chenyu_3108 小时前
12.找到字符串中所有字母异位词
c语言·数据结构·算法·哈希算法
苏三福8 小时前
yolo11-seg ultralytics 部署版本
算法·yolo11
wuqingshun31415911 小时前
蓝桥杯 冶炼金属
算法·职场和发展·蓝桥杯