forked from cheungYX/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinStack.java
60 lines (51 loc) · 1.34 KB
/
MinStack.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
// version 1:
public class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<Integer>();
minStack = new Stack<Integer>();
}
public void push(int number) {
stack.push(number);
if (minStack.isEmpty()) {
minStack.push(number);
} else {
minStack.push(Math.min(number, minStack.peek()));
}
}
public int pop() {
minStack.pop();
return stack.pop();
}
public int min() {
return minStack.peek();
}
}
// version 2, save more space. but space complexity doesn't change.
public class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<Integer>();
minStack = new Stack<Integer>();
}
public void push(int number) {
stack.push(number);
if (minStack.empty() == true)
minStack.push(number);
else {
// 这里考虑的相等的情况也会继续push
if (minStack.peek() >= number)
minStack.push(number);
}
}
public int pop() {
if (stack.peek().equals(minStack.peek()) )
minStack.pop();
return stack.pop();
}
public int min() {
return minStack.peek();
}
}