Skip to content
New issue

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

[剑指 Offer] 30. 包含min函数的栈 #60

Open
frdmu opened this issue Aug 1, 2021 · 0 comments
Open

[剑指 Offer] 30. 包含min函数的栈 #60

frdmu opened this issue Aug 1, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Aug 1, 2021

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 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.

提示:

  • 各函数的调用总次数不超过 20000 次


解法:
虽然是简单题,但是我还真没想出来,这就是菜鸡吧!解决方法是用两个栈,一个辅助栈栈顶存当前的最小值。代码如下:

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();
 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant