本文主要是介绍LeetCode *** 155. 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.
分析:
最小值只与pop与push有关。
代码:
class MinStack {
public:stack<int> s1,s2;void push(int x) {s1.push(x);if(s2.empty()||x<=getMin())s2.push(x);}void pop() {if(s1.top()==s2.top()){s2.pop();}s1.pop();}int top() {return s1.top();}int getMin() {return s2.top();}
};
这篇关于LeetCode *** 155. Min Stack的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!