设计得到最小值的栈

设计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();
    }
}
全部评论

相关推荐

焦虑中,不知道怎么办了。。。
西北上单:应该放俩项目合理一些 我是一个业务开发项目 一个AI项目和你这个写的亮点差不多
你的简历改到第几版了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
03-19 10:38
实力求职者:真的绷不住了,第一张霸总人设,第二张求生欲拉满
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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