剑指Offer20包含min函数的栈
Posted blog-cpc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指Offer20包含min函数的栈相关的知识,希望对你有一定的参考价值。
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
题解:辅助栈
1 private static Stack<Integer> stack = new Stack<>(); 2 private static Stack<Integer> minNum=new Stack<>(); 3 public static void push(int node) { 4 stack.push(node); 5 //minNum存放当前的最小元素 6 if(minNum.isEmpty()){ 7 minNum.push(stack.peek()); 8 } 9 else if(stack.peek()<minNum.peek()){ 10 minNum.push(stack.peek()); 11 } 12 else { 13 minNum.push(minNum.peek()); 14 } 15 } 16 public static void pop() { 17 if(!stack.isEmpty()){ 18 stack.pop(); 19 } 20 //同步弹出元素 21 minNum.pop(); 22 } 23 public static int top() { 24 return stack.peek(); 25 } 26 public static int min() { 27 return minNum.peek(); 28 }
测试:
1 public static void main(String[] args) { 2 String[] order={"PSH_3","MIN","PSH_4","MIN","PSH_2","MIN","PSH_3","MIN","POP","MIN","POP","MIN","POP","MIN","PSH_0","MIN"}; 3 for(int i=0;i<order.length;i++){ 4 String s = order[i].toString(); 5 String[] strings = s.split("_"); 6 if(strings[0].equals("PSH")){ 7 int parseInt = Integer.parseInt(strings[1]); 8 push(parseInt); 9 } 10 if(strings[0].equals("POP")){ 11 pop(); 12 } 13 if(strings[0].equals("MIN")){ 14 int min = min(); 15 System.out.print(min+" "); 16 } 17 } 18 } 19 输出:3 3 2 2 2 3 3 0
以上是关于剑指Offer20包含min函数的栈的主要内容,如果未能解决你的问题,请参考以下文章