【算法】查找栈内最小值的O(1)算法————用辅助栈实现

来源:互联网 发布:食品代加工 知乎 编辑:程序博客网 时间:2024/06/08 20:00

查找栈内最小值的O(1)算法————用辅助栈实现

具体实现方式有二,但两者区别仅在于入栈出栈的方式,思路均为通过一个辅助栈来实现存储原栈的最小值,辅助栈的栈顶永远为当前栈的最小值。

(设辅助栈为stackMin,原栈为stackData)

方式一:stackData每压入一个数,就比较该数与stackMin栈顶的大小(如果stackMin为空,就直接压入),如果小就压入stackPop中,否则略过;每弹出一个数,就比较该数与stackMin栈顶的大小是否相等,如果相等就同时弹出stackMin的栈顶,否则略过

代码实现如下:

package com.lilydedbb;import java.util.Stack;/** * Created by dbb on 2016/12/23. */public class GetMinStack {    private Stack<Integer> stackData;    private Stack<Integer> stackMin;    public GetMinStack(){        this.stackData = new Stack<Integer>();        this.stackMin = new Stack<Integer>();    }    public void push(int newNumber){        this.stackData.push(newNumber);        if(this.stackMin.isEmpty() || newNumber <= this.getMin())            this.stackMin.push(newNumber);    }    public int pop(){        if(this.stackData.isEmpty())            throw new RuntimeException("The stack is empty");        int number = this.stackData.pop();        if (number == this.getMin())            this.stackMin.pop();        return number;    }    public int getMin(){        if(this.stackMin.isEmpty())            throw new RuntimeException("The stack is empty");        return this.stackMin.peek();    }}

方式二:stackData每压入一个数,就比较该数与stackMin栈顶的大小(如果stackMin为空,就直接压入),如果小就压入stackPop中,否则继续压入上一次压入的最小值;每弹出一个数,就同时弹出stackMin的栈顶

代码实现如下:

package com.lilydedbb;import java.util.Stack;/** * Created by dbb on 2016/12/23. */public class GetMinStack2 {    private Stack<Integer> stackData;    private Stack<Integer> stackMin;    public GetMinStack2(){        this.stackData = new Stack<Integer>();        this.stackMin = new Stack<Integer>();    }    public void push(int newNumber){        this.stackData.push(newNumber);        if(this.stackMin.isEmpty() || newNumber <= this.getMin()){            this.stackMin.push(newNumber);        }else{            this.stackMin.push(this.getMin());        }    }    public int pop(){        if(this.stackData.isEmpty())            throw new RuntimeException("The stack is empty");        this.stackMin.pop();        return this.stackData.pop();    }    public int getMin(){        if(this.stackMin.isEmpty())            throw new RuntimeException("The stack is empty");        return this.stackMin.peek();    }}

方式一与方式二都在保证辅助栈的栈顶均为最小值,区别仅在于pushpop时的策略不同。

0 0
原创粉丝点击