Leetcode 155. Min Stack

在这里插入图片描述
方法1: pair。其实这道题最重要的就是要track 最小值并保存下来,所以一定需要额外空间。时间复杂1,空间复杂n。详细解释直接看lc官方解答。

class MinStack {
    Stack<int[]> stack = new Stack<>();
    /** initialize your data structure here. */
    public MinStack() {
        
    }
    
    public void push(int x) {
        if(stack.isEmpty()) stack.push(new int[]{x, x});
        else {
            int[] curr = new int[]{x, Math.min(x, stack.peek()[1])};
            stack.push(curr);
        }
    }
    
    public void pop() {
        stack.pop();
    }
    
    public int top() {
        return stack.peek()[0];
    }
    
    public int getMin() {
        return stack.peek()[1];
    }
}

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

方法2: two stack。方法1的优化。时间复杂1,空间复杂n。

class MinStack {
    Stack<Integer> s = new Stack<>();
    Stack<Integer> mStack = new Stack<>();
    /** initialize your data structure here. */
    public MinStack() {
        
    }
    
    public void push(int x) {
        if(s.isEmpty() && mStack.isEmpty()){
            s.push(x);
            mStack.push(x);
        }else{
            if(x <= mStack.peek()){
                s.push(x);
                mStack.push(x);
            }else{
                s.push(x);
            }
        }
    }
    
    public void pop() {
        int curr = s.pop();
        if(curr == mStack.peek()) mStack.pop();
    }
    
    public int top() {
        return s.peek();
    }
    
    public int getMin() {
        return mStack.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();
 */

方法3: two stacks + pair,方法3的优化。时间复杂1,空间复杂n。

class MinStack {
    Stack<Integer> s = new Stack<>();
    Stack<int[]> mStack = new Stack<>();
    /** initialize your data structure here. */
    public MinStack() {
        
    }
    
    public void push(int x) {
        s.push(x);
        if(mStack.isEmpty() || x < mStack.peek()[0]){
            mStack.push(new int[]{x,1});
        }else if(x == mStack.peek()[0]){
            mStack.peek()[1]++;
        }
    }
    
    public void pop() {
        int curr = s.pop();
        if(curr == mStack.peek()[0]) mStack.peek()[1]--;
        if(mStack.peek()[1] == 0) mStack.pop();
    }
    
    public int top() {
        return s.peek();
    }
    
    public int getMin() {
        return mStack.peek()[0];
    }
}

/**
 * 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();
 */
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页