-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinStack_155.java
57 lines (46 loc) · 1.39 KB
/
MinStack_155.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
/**
* XXXXXXXXXXXXX $$$$$$$I did not figure out the solution at all at first!
* Using two stacks & record the state!
*
* XXXXXXXXXstack.peek() not peak()
*
* IMPROVEMENT: Do not need to repeatedly push the min value, only need one copy;
*/
/*class MinStack {
Stack<Integer> stack;
Stack<Integer> minstack;
MinStack() { stack = new Stack<>(); minstack = new Stack<>(); }
public void push(int x) {
stack.push(x);
minstack.push(minstack.isEmpty() ? x : Math.min(x, minstack.peek()));
}
public void pop() {
stack.pop(); minstack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minstack.peek();
}
}*/
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minstack;
MinStack() { stack = new Stack<>(); minstack = new Stack<>(); }
public void push(int x) {
stack.push(x);
if (minstack.isEmpty() || x <= minstack.peek()) minstack.push(x);
}
public void pop() {
// if (stack.peek() == minstack.peek()) minstack.pop(); // XXXXXX you can not use == here, they are two objects!!!
if (stack.peek().equals(minstack.peek())) minstack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minstack.peek();
}
}