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

相关推荐

2025-12-10 19:36
湖北工业大学 Web前端
饿魔:看到在线简历了吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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