在实现栈中原来功能的基础上,获得一个栈中最小值,要求时间复杂度 bigO(1)

思路:

  准备两个栈 stackData stackMin

 1 package my_basic;
 2 
 3 import java.util.Stack;
 4 
 5 public class GetMinStack {
 6     Stack<Integer> stackData = new Stack<Integer>();
 7     Stack<Integer> stackMin = new Stack<Integer>();
 8     
 9     public void push(int pushInt) {
10         if (stackMin.empty()) {
11             stackMin.push(pushInt);
12         }else if (pushInt < stackMin.peek()) {
13             stackMin.push(pushInt);
14         }else {
15             stackMin.push(stackMin.peek());
16         }
17         stackData.push(pushInt);
18     }
19     
20     public int pop() {
21         if (stackData.empty()) {
22             throw new RuntimeException("stack is empty!");
23         }
24         stackMin.pop();
25         return stackData.pop();
26     }
27     
28     public int getMin() {
29         if (stackData.empty()) {
30             throw new RuntimeException("stack is empty!");
31         }
32         return stackMin.peek();
33     }
34     
35     public static void main(String[] args) {
36         GetMinStack s = new GetMinStack();
37         s.push(6);
38         s.push(5);
39         s.push(2);
40         
41         int res = s.getMin();
42         System.out.println(res);
43         
44         s.push(7);
45         
46         res =  s.getMin();
47         System.out.println(res);
48         
49         s.pop();
50         s.pop();
51         
52         res =  s.getMin();
53         System.out.println(res);
54     }
55     
56 }
原文地址:https://www.cnblogs.com/lihuazhu/p/10763506.html