【剑指Offer】20、包含min函数的栈

题目描述

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

注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。

题解:辅助栈
 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 

猜你喜欢

转载自www.cnblogs.com/Blog-cpc/p/12377988.html