题解 | 包含min函数的栈

包含min函数的栈

https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49

import java.util.*;
import java.util.Stack;

public class Solution {
    HashMap<Integer, Integer> map;
    Stack<Integer> stack;
    Stack<Integer> stack2;
    int minValue;
    public Solution() {
        this.map = new HashMap<>();
        this.stack = new Stack<>();
        this.stack2 = new Stack<>();
        this.minValue = Integer.MAX_VALUE;
    }

    public void push(int node) {
        stack.push(node);
        if (stack2.isEmpty() || node <= stack2.peek()) {
            stack2.push(node);
        } else {
            stack2.push(stack2.peek());
        }
    }

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

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

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

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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