本文主要是介绍716. 最大栈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
类型:双栈
难度:简单
题意:使用两个栈,一个存最大值,一个存原值。
class MaxStack {
public:/** initialize your data structure here. */MaxStack() {}stack<int> buf;stack<int> stk, max_stk;void push(int x) {stk.push(x);if(max_stk.empty()) max_stk.push(x);else max_stk.push(max(x, max_stk.top()));}int pop() {max_stk.pop();int t = stk.top();stk.pop();return t; }int top() {return stk.top();}int peekMax() {return max_stk.top();}int popMax() {int t = max_stk.top();while(stk.size() && stk.top()!= t){buf.push(stk.top());stk.pop();max_stk.pop();}stk.pop();max_stk.pop();while(buf.size()){push(buf.top());buf.pop();}return t;}
};/*** Your MaxStack object will be instantiated and called as such:* MaxStack* obj = new MaxStack();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->top();* int param_4 = obj->peekMax();* int param_5 = obj->popMax();*/
这篇关于716. 最大栈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!