[LeetCode] 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.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

最小栈,要求getMin()为检索当前stack中的最小值。

每次添加元素时用minValue来维护一个最小值

在弹出元素时,如果弹出的是最小元素,则需要在弹出后的stack中找出最小值,因为stack不能遍历,所以使用另一个tmpStack来存储原stack中弹出的每一个值找出最小元素。在将tmpStack中的值再传给原stack中。权当是一个遍历。

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        minValue = INT_MAX;
    }
    
    void push(int x) {
        s.push(x);
        minValue = min(minValue, x);
    }
    
    void pop() {
        int tmp = s.top();
        s.pop();
        if (tmp >= minValue) {
            int minVal = INT_MAX;
            while (!s.empty()) {
                tmpS.push(s.top());
                minVal = min(minVal, s.top());
                s.pop();
            }
            minValue = minVal;
        }
        while (!tmpS.empty()) {
            s.push(tmpS.top());
            tmpS.pop();
        }
        
    }
    
    int top() {
        return s.top();
    }
    
    int getMin() {
        return minValue;
    }
    
private:
    stack<int> s;
    stack<int> tmpS;
    int minValue;
};
// 29 ms
/**
 * 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.getMin();
 */
class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> m_data;
    stack<int> m_min;
    MinStack() {
        
    }
    
    void push(int x) {
        m_data.push(x);
        if (m_min.empty() || x < m_min.top())
            m_min.push(x);
        else
            m_min.push(m_min.top());
    }
    
    void pop() {
        m_data.pop();
        m_min.pop();
    }
    
    int top() {
        return m_data.top();
    }
    
    int getMin() {
        return m_min.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.getMin();
 */
原文地址:https://www.cnblogs.com/immjc/p/7994639.html