leetcode - Min Stack
LeetCode Stack min
2023-09-27 14:27:02 时间
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
class MinStack { public: struct Node { int val; int cntEmlem; Node(int value,int count) : val(value),cntEmlem(count){} }; void push(int x) { stk.push(x); if(minStk.empty() || x < minStk.top().val) { Node n(x,1); minStk.push(n); } else { Node n = minStk.top(); n.cntEmlem++; minStk.pop(); minStk.push(n); } } void pop() { stk.pop(); Node n = minStk.top(); minStk.pop(); n.cntEmlem--; if(n.cntEmlem > 0) { minStk.push(n); } } int top() { return stk.top(); } int getMin() { return minStk.top().val; } private: std::stack<int> stk; std::stack<Node> minStk; };
版权声明:本文博主原创文章。博客,未经同意不得转载。
相关文章
- LeetCode 481. 神奇字符串
- LeetCode_栈_中等_1003.检查替换后的词是否有效
- LeetCode_动态规划_困难_10.正则表达式匹配
- LeetCode_双指针_中等_18.四数之和
- LeetCode·每日一题·1582.二进制矩阵中的特殊位置·模拟
- [LeetCode] 495. Teemo Attacking 提莫攻击
- [LeetCode] 490. The Maze 迷宫
- [LeetCode] 259. 3Sum Smaller 三数之和较小值
- [LeetCode] 72. Edit Distance 编辑距离
- [LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先