JZ20 包含min函数的栈, 辅助栈

包含min函数的栈

http://www.nowcoder.com/questionTerminal/4c776177d2c04c2494f2555c9fcc1e49

解法一:同步辅助栈

import java.util.Stack;

public class Solution {  
    Stack<Integer> stack=new Stack<>();
    Stack<Integer> helper=new Stack<>();
    public void push(int node) {
        stack.push(node);
        if(helper.isEmpty()) helper.push(node);
        else helper.push(Math.min(helper.peek(),node));
    }

    public void pop() {
        stack.pop();
        helper.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int min() {
        return helper.peek();
    }
}

解法二:非同步辅助栈

import java.util.Stack;

public class Solution {  
    Stack<Integer> stack=new Stack<>();
    Stack<Integer> helper=new Stack<>();
    public void push(int node) {
        stack.push(node);
        if(helper.isEmpty()||helper.peek()>=node)
            helper.push(node);
    }

    public void pop() {
        int t=stack.pop();
        if(t==helper.peek()) helper.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int min() {
        return helper.peek();
    }
}

Java中栈的推荐使用方法

Deque<T> stack=new ArrayDeque<>();
全部评论

相关推荐

04-03 09:32
已编辑
华南农业大学 golang
我的代码出BUG了:"晚点发个邮件调整一下时间",你收到新的邮件没,如果没有收到新的邮件,那就需要进入面试链接留痕,否则系统会判定你迟到
点赞 评论 收藏
分享
站队站对牛:进度也算很慢的了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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