设计得到最小值的栈

设计getMin功能的栈

http://www.nowcoder.com/questionTerminal/c623426af02d4c189f92f2a99647bd34

有两种方法:
一是只使用一个栈,栈里存储的是一个数组,保存最小值和当前值,最小值是在push时候判断的。

public class Solution {
    /**
     * return a array which include all ans for op3
     * @param op int整型二维数组 operator
     * @return int整型一维数组
     */
    //只利用一个栈保存最小值和当前值
    Stack<int[]> stack = new Stack<>();
    ArrayList<Integer> list = new ArrayList<>();
    public int[] getMinStack (int[][] op) {
        // write code here
        for(int[] opt : op){
            if(opt[0] == 1)
                push(opt[1]);
            else if(opt[0] == 2)
                pop();
            else
                list.add(getMin());
        }
        int[] res = new int[list.size()];
        for(int i = 0; i < list.size(); i++){
            res[i] = list.get(i);
        }
        return res;
    }

    public void push(int value){
        if(stack.isEmpty()){
            stack.push(new int[]{value, value});
        }else{
            stack.push(new int[]{value, Math.min(value, stack.peek()[1])});
        }
    }

    public void pop(){
        stack.pop();
    }
    public int getMin(){
        return stack.peek()[1];
    }
}

二是利用多一个栈来存储最小值。
public class Solution {
    /**
     * return a array which include all ans for op3
     * @param op int整型二维数组 operator
     * @return int整型一维数组
     */
    //只利用一个栈保存最小值和当前值
    Stack<Integer> stackMin = new Stack<>();
    Stack<Integer> stackCur = new Stack<>();
    ArrayList<Integer> list = new ArrayList<>();
    public int[] getMinStack (int[][] op) {
        // write code here
        for(int[] opt : op){
            if(opt[0] == 1)
                push(opt[1]);
            else if(opt[0] == 2)
                pop();
            else
                list.add(getMin());
        }
        int[] res = new int[list.size()];
        for(int i = 0; i < list.size(); i++){
            res[i] = list.get(i);
        }
        return res;
    }

    public void push(int value){
        stackCur.push(value);
        if(stackMin.isEmpty() || value < stackMin.peek()){
            stackMin.push(value);
        }
    }

    public void pop(){
        int cur = stackCur.pop();
        if(!stackMin.isEmpty() && cur == stackMin.peek()){
            stackMin.pop();
        }
    }
    public int getMin(){
        return stackMin.peek();
    }
}
全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 14:00
林子大了什么鸟都有啊,我觉得我说的已经很客气了,阴阳谁呢
牛客62656195...:应该不是阴阳吧?你第一次注册的时候boss就说你是牛人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务