剑指offer JZ20 包含min函数的栈
发布日期:2021-05-07 13:14:32 浏览次数:17 分类:原创文章

本文共 762 字,大约阅读时间需要 2 分钟。

包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

代码

public class Solution {       Stack<Integer> stack = new Stack<Integer>();//栈需要泛型,不能是int    Stack<Integer> minstack = new Stack<Integer>();        public void push(int node) {           stack.push(node);        if(minstack.isEmpty()){               minstack.push(node);        }else{               if(node<minstack.peek()){    //top()方法 不可用                minstack.push(node);            }        }    }        public void pop() {   //主栈元素直接弹出,min栈        int temp = stack.pop();        if(temp==minstack.peek()) minstack.pop();    }        public int top() {           return stack.peek();    }        public int min() {           return minstack.peek();    }}

突破点

栈没有top()方法
入栈时选出元素值小的加入到另一个栈中存放

上一篇:剑指 offer JZ22 从上往下打印二叉树
下一篇:剑指offer JZ21 栈的压入弹出序列

发表评论

最新留言

很好
[***.229.124.182]2025年03月30日 17时52分08秒