LeetCode 155 minimum stack (Java implementation)

Title description:

Title description

Method One (ArrayList):
Code:

class MinStack {
    
    
    ArrayList<Integer> list;

    /** initialize your data structure here. */
    public MinStack() {
    
    
        list = new ArrayList<Integer>();
    }
    
    public void push(int x) {
    
    
        list.add(x);
    }
    
    public void pop() {
    
    
        list.remove(list.size()-1);
    }
    
    public int top() {
    
    
        return list.get(list.size()-1);
    }
    
    public int getMin() {
    
    
        int min = Integer.MAX_VALUE;;
        for(Integer i : list){
    
    
            if(i<min){
    
    
                min = i;
            }
        }
        return min;
    }
}

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

result:

result

Method two (Deque):

Use this method to pay attention to: eliminate the impact of the minimum number of each pop of the stack, so a mindq is established to store the minimum number generated after each push of an element, so that after each pop of the deque, mindq will also Pop off the minimum value generated by the elements of deque pop, and the top of the mindq stack is still the minimum number of the current deque.

class MinStack {
    
    
    Deque<Integer> deque;
    Deque<Integer> mindq;

    /** initialize your data structure here. */
    public MinStack() {
    
    
        deque = new LinkedList<Integer>();
        mindq = new LinkedList<Integer>();
        mindq.push(Integer.MAX_VALUE);
    }
    
    public void push(int x) {
    
    
        deque.push(x);
        mindq.push(Math.min(mindq.peek(),x));
    }
    
    public void pop() {
    
    
        deque.pop();
        mindq.pop();
    }
    
    public int top() {
    
    
        return deque.peek();
    }
    
    public int getMin() {
    
    
        return mindq.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();
 */

result:
result

Guess you like

Origin blog.csdn.net/weixin_43752257/article/details/110448704