155. 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.

读题…注意… 仅仅是min的时候时间复杂度是O(1) 这样的话…很直观能想到用两个栈来存…一个栈存迄今最小的…一个栈存数据。有人用一个栈的…但是感觉没什么卵用,无非是遇到最小的,把最小的push两次,出栈是最小的时候,pop两次最小…如果是实现最大栈呢…?
有一个细节… pop出来两个Integer… 直接等要出问题…需要转型

class MinStack {

    Stack stack = new Stack<>();
    Stack min = new Stack<>();

    public void push(int x) {
        if(min.isEmpty() || min.peek() >= x)min.push(x);
        stack.push(x);
    }
    
    public void pop() {
        //卧槽太细节了!!
        if((int)stack.peek() == (int)min.peek())min.pop();
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return min.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();
 */

你可能感兴趣的:(数据结构与算法)