forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MiniStack.java
77 lines (60 loc) · 1.83 KB
/
MiniStack.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package Algorithms;
import java.util.Stack;
public class MiniStack {
// reference: http://stackoverflow.com/questions/685060/design-a-stack-such-that-getminimum-should-be-o1
Stack<Integer> s = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
public static void main(String[] strs) {
MiniStack s = new MiniStack();
s.push(2);
System.out.println(s.min());
s.push(6);
System.out.println(s.min());
s.push(4);
System.out.println(s.min());
s.push(1);
System.out.println(s.min());
s.push(5);
System.out.println(s.min());
s.push(1);
System.out.println(s.min());
System.out.println("BEGINE POP");
System.out.println(s.pop());
System.out.println(s.min());
System.out.println(s.pop());
System.out.println(s.min());
System.out.println(s.pop());
System.out.println(s.min());
System.out.println(s.pop());
System.out.println(s.min());
System.out.println(s.pop());
System.out.println(s.min());
System.out.println(s.pop());
System.out.println(s.min());
}
public MiniStack() {
// do initialize if necessary
super();
}
public void push(int number) {
// write your code here
if (s.isEmpty() || number <= minStack.peek()) {
minStack.push(number);
}
s.push(number);
}
public int pop() {
// write your code here
if (s.peek() == minStack.peek()) {
minStack.pop();
}
return s.pop();
}
public int min() {
// write your code here
if (minStack.isEmpty()) {
return Integer.MAX_VALUE;
}
return minStack.peek();
}
}