题解 | #包含min函数的栈# | 两个栈

包含min函数的栈

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

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

public class Solution {

     /**
     * 两个栈  一个用于一直往里面放元素  另一个构造递减的栈
     */
    Stack<Integer> mainStack = new Stack<>();

    Stack<Integer> otherStack = new Stack<>();

    public void push(int node) {
        if (otherStack.isEmpty() || otherStack.peek() >= node) {
            otherStack.push(node);
        }
        mainStack.push(node);
    }

    public void pop() {
        Integer pop = mainStack.pop();
        if (pop.equals(otherStack.peek())) {
            otherStack.pop();
        }
    }

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

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

基本思路

构造两个栈,一个正常的栈,存放放入的数据,一个递减栈,如果当前压入的值比当前递减栈的栈顶值大,则不压入,因为不可能是当前及以后的栈的最小值

全部评论

相关推荐

缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
那一天的Java_J...:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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