LeetCode-155.Min Stack
来源:互联网 发布:重庆行知教育集团 编辑:程序博客网 时间:2024/04/30 12:31
https://leetcode.com/problems/min-stack/
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.
用一个栈存放数据,另一个栈存放最小值。注意栈空的情况
class MinStack{public: stack<int> s, minS; int minVal = 2147483647; /** initialize your data structure here. */ MinStack() { } void push(int x) { s.push(x); if (x < minVal) minVal = x; minS.push(minVal); } void pop() { s.pop(); minS.pop(); if(s.empty()) minVal = 2147483647;else minVal = minS.top(); } int top() { return s.top(); } int getMin() { if (s.empty()) return 2147483647; else return minS.top(); }};
也可以不使用minVal,事先在最小值栈底存放2147483647
class MinStack{public: stack<int> s, minS; /** initialize your data structure here. */ MinStack() { minS.push(2147483647); } void push(int x) { s.push(x); if (x < minS.top()) minS.push(x); else minS.push(minS.top()); } void pop() { s.pop(); minS.pop(); } int top() { return s.top(); } int getMin() { return minS.top(); }};
只用一个栈实现 参考https://leetcode.com/discuss/21071/java-accepted-solution-using-one-stack
class MinStack{public: stack<int> s; int minVal = 2147483647; /** initialize your data structure here. */ MinStack() { } void push(int x) { if (x <= minVal) { s.push(minVal); minVal = x; } s.push(x); } void pop() { if (minVal == s.top()) { s.pop(); minVal = s.top(); } s.pop(); //if (s.empty()) //minVal = 2147483647; } int top() { return s.top(); } int getMin() { return minVal; }};
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
- 【iOS开发】Foreign famous blogs
- Android 判断View是否被遮挡
- 第14周项目 2—数组类模板
- 在raspberry运行xibo
- weblogic解决Jar包冲突
- LeetCode-155.Min Stack
- 论big data 3.0取代SAP HANA的可行性
- 大数据Kafka
- C++ eof()函数相关应用技巧分享
- getCacheDir()、getFilesDir()、getExternalFilesDir()
- [读书笔记]《Java程序员修炼之道》
- SpringMVC 基于注解的Controller详解
- TableViewCell 复用解决
- Android学习笔记--GMS认证(常见的cts—fail及解决方法)