【leetcode】155. Min Stack
来源:互联网 发布:国家邮政局投诉知乎 编辑:程序博客网 时间:2024/05/16 11:04
一、题目描述
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.
Example:
MinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.getMin(); --> Returns -3.minStack.pop();minStack.top(); --> Returns 0.minStack.getMin(); --> Returns -2.
题目解读:写一个栈要有以下功能:push(),pop(),top(),getMin()能取得当前栈中的最小元素
思路:直接用一个栈就可以实现所有的push(),pop(),top()这三个功能,在设置一个栈用来存每加入一个元素时当前的最小元素。因此在每pop一个元素对于min栈也要pop一个元素。
c++代码(52ms,74.75%)
class MinStack {public: /** initialize your data structure here. */ stack<int> min; stack<int> result; void push(int x) { result.push(x); if(min.empty()) min.push(x); else{ if(x<min.top()) min.push(x); else{ min.push(min.top()); }//else }//else }//void void pop() { result.pop(); min.pop(); } int top() { return result.top(); } int getMin() { return min.top(); }};/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
其他代码:
class MinStack {private: stack<int> s1; stack<int> s2;public: void push(int x) { s1.push(x); if (s2.empty() || x <= getMin()) s2.push(x); } void pop() { if (s1.top() == getMin()) s2.pop(); s1.pop(); } int top() { return s1.top(); } int getMin() { return s2.top(); }};
0 0
- LeetCode 155. Min Stack
- 【LeetCode】155.Min Stack
- LeetCode 155.Min Stack
- [leetcode] 155.Min Stack
- [leetcode] 155.Min Stack
- Leetcode 155. Min Stack
- 155. Min Stack LeetCode
- [LeetCode]155. Min Stack
- LeetCode *** 155. Min Stack
- 【leetcode】155. Min Stack
- LeetCode 155. Min Stack
- leetcode-155. Min Stack
- LeetCode-155.Min Stack
- LeetCode - 155. Min Stack
- [Leetcode]155. Min Stack
- 【leetcode】155. Min Stack
- LeetCode 155. Min Stack
- [leetcode] 155. Min Stack
- Mysql表结构优化
- java I/O流(4) RandomAccessFile
- LeetCode进阶之路(ZigZag Conversion)
- 【javascript]-Dom的编辑
- 区块链开发(一)搭建基于以太坊的私有链环境
- 【leetcode】155. Min Stack
- Poj1386 Play on Words
- find -name a.txt的误用(没考虑软链), 导致浪费0.5小时
- 5.3 输入/输出(I/O)管理
- LCA-倍增思想 POJ1330 Nearest Common Ancestors
- src
- TimesTen 数据库复制学习:17. 更改classic复制
- Properties的解耦实验
- 21. Merge Two Sorted Lists