力扣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;
      }
  };
相关推荐
console.log('npc')2 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
橘子133 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘15 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴18 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David18 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
LK_0721 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi21 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK21 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
文丑颜不良啊1 天前
LeetCode3341~3360题目解析
java·leetcode
上海潭龙东海科技有限公司1 天前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构