[The sword refers to the offer brushing the question] AcWing 41. The stack including the min function (simulation question, the application of the queue and the stack)

ideas

Using two stacks can be a good solution

topic

Design a stack that supports push, pop, top, etc. operations and can retrieve the smallest element in O(1) time.

push(x)–将元素x插入栈中
pop()–移除栈顶元素
top()–得到栈顶元素
getMin()–得到栈中最小元素

data range

The total number of operation commands [0,100].
Example

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

code

class MinStack {
    
    

    /** initialize your data structure here. 
    * 使用两个栈:
    *   1. 第一个栈用来记录栈元素
    *   2. 第二个栈用来记录最小值
    **/
    
    private Stack<Integer> s1 = new Stack<Integer>();
    private Stack<Integer> s2 = new Stack<Integer>();
    
    public MinStack() {
    
    
        
    }
    
    public void push(int x) {
    
    
        s1.push(x);
        if (!s2.empty())
            s2.push(Math.min(x, s2.peek()));
        else
            s2.push(x);
    }
    
    public void pop() {
    
    
        s1.pop();
        s2.pop();
    }
    
    public int top() {
    
    
        return s1.peek();
    }
    
    public int getMin() {
    
    
        return s2.peek();
    }
}

/**
 * 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();
 */

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326124114&siteId=291194637