30-Day Leetcoding Challenge Day10

三种解法:

第一种:用了Stack<int[x,y]>这样的数据结构,其中y为栈中当前最小值

第二种:用了两个栈为stack<Integer> 和minstack<Integer>,其中minstack存储stack的当前最小值

第三种:用了Stack<Integer>和minStack<int [ ]>

class MinStack {

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

 

注意 ‘==’ 和 equals的区别;equals是判断两个变量或实例指向同一个内存空间的值是不是相同,==是判断两个变量或实例是不是指向同一个内存空间

class MinStack {

    /** initialize your data structure here. */
    private Stack<Integer> stack = new Stack<>();
    private Stack<Integer> minstack = new Stack<>();
    
    //public MinStack(){}
    
    public void push(int x) {
        if(stack.isEmpty() || x <= minstack.peek()){
            minstack.push(x);
        }
        stack.push(x);
    }
    
    public void pop() {
        if(stack.peek().equals(minstack.peek())){ //bug ==比的是引用,equals比的是值
            minstack.pop();
        }
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return minstack.peek();
    }  
}

 

class MinStack {

    /** initialize your data structure here. */
    private Stack<Integer> stack = new Stack<>();
    private Stack<int[]> minstack = new Stack<>();
    
    //public MinStack(){}
    
    public void push(int x) {
        if(stack.isEmpty() || x <= minstack.peek()[0]){
            minstack.push(new int[]{x, 1});
        }
        else if(x == minstack.peek()[0]){
            minstack.peek()[1]++;
        }
        stack.push(x);
    }
    
    public void pop() {
        if(stack.peek().equals(minstack.peek()[0])){ //bug ==比的是引用,equals比的是值
            minstack.peek()[1]--;
        }
        if(minstack.peek()[1] == 0){
            minstack.pop();
        }
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return minstack.peek()[0];
    }  
}

 

posted @ 2020-04-15 18:32  yawenw  阅读(98)  评论(0编辑  收藏  举报