Passion and Patience

Work Hard, Play Hard

导航

Leetcode 最小栈

Day 8 第二题

我的思路:用栈来定义栈的相关操作,但超出运行时间,考虑原因是克隆栈(Stack<Integer>) xx.clone();消耗的时间和空间复杂度。原来stack有get函数!
// 定义一个类MinStack
class MinStack {
    public Stack<Integer> newobj = new Stack<Integer>();

    public MinStack() {     
        // 无参构造器
    }
    
    public void push(int val) {
        newobj.push(val);
    }
    
    public void pop() {
        newobj.pop();
    }
    
    public int top() {
        return newobj.peek();
    }
    
    public int getMin() {
        Stack<Integer> tempObj = (Stack<Integer>) newobj.clone();
        int minVal = tempObj.peek();
        while( ! tempObj.isEmpty() ){
            minVal = minVal>(tempObj.peek())?tempObj.peek():minVal;
            tempObj.pop();          
        }
    return minVal;
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */
力扣官方解题:引入第二个辅助栈
class MinStack {
    Deque<Integer> xStack;
    Deque<Integer> minStack;

    public MinStack() {
        xStack = new LinkedList<Integer>();
        minStack = new LinkedList<Integer>();
        minStack.push(Integer.MAX_VALUE);
    }
    
    public void push(int x) {
        xStack.push(x);
        minStack.push(Math.min(minStack.peek(), x));
    }
    
    public void pop() {
        xStack.pop();
        minStack.pop();
    }
    
    public int top() {
        return xStack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
}

posted on 2024-03-23 23:56  安静的聆  阅读(11)  评论(0)    收藏  举报