本文主要是介绍155. Min Stack包含min函数的栈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
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.
解答
void push(int value) {dataStack.push(value);if(minStack.empty() || value<minStack.top())minStack.push(value);elseminStack.push(minStack.top());}void pop() {if(!dataStack.empty())dataStack.pop();if(!minStack.empty())minStack.pop();}int top() {return dataStack.top();}int min() {return minStack.top();}stack<int> dataStack;stack<int> minStack;
这篇关于155. Min Stack包含min函数的栈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!