We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.min(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.min(); --> 返回 -2.
提示:
解法: 虽然是简单题,但是我还真没想出来,这就是菜鸡吧!解决方法是用两个栈,一个辅助栈栈顶存当前的最小值。代码如下:
class MinStack { public: stack<int> stk; stack<int> minStk; /** initialize your data structure here. */ MinStack() { } void push(int x) { stk.push(x); if (minStk.empty()) { minStk.push(x); } else { minStk.push(x < minStk.top() ? x : minStk.top()); } } void pop() { stk.pop(); minStk.pop(); } int top() { return stk.top(); } int min() { return minStk.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->min(); */
The text was updated successfully, but these errors were encountered:
No branches or pull requests
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
提示:
解法:
虽然是简单题,但是我还真没想出来,这就是菜鸡吧!解决方法是用两个栈,一个辅助栈栈顶存当前的最小值。代码如下:
The text was updated successfully, but these errors were encountered: