-
-
Notifications
You must be signed in to change notification settings - Fork 315
/
Copy pathStackMin.java
62 lines (52 loc) · 1.43 KB
/
StackMin.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
package com.ctci.stacksandqueues;
import com.sun.tools.javac.util.Assert;
import java.util.Stack;
/**
* How would you design a stack which, in addition to push and pop, has a function min
* which returns the minimum element? Push, pop and min should all operate in 0(1) time.
*
* @author rampatra
* @since 2019-02-04
*/
public class StackMin {
// the main stack to do push, pop, and min operations
private static Stack<Integer> stack = new Stack<>();
// another stack to store the mins (needed to make min() call O(1))
private static Stack<Integer> minStack = new Stack<>();
private static int push(int item) {
minPush(item);
return stack.push(item);
}
private static int pop() {
minPop(stack.peek());
return stack.pop();
}
private static int min() {
return minStack.peek();
}
private static void minPush(int item) {
if (minStack.empty() || item <= minStack.peek()) {
minStack.push(item);
}
}
private static void minPop(int item) {
if (item == minStack.peek()) {
minStack.pop();
}
}
public static void main(String[] args) {
push(2);
push(5);
push(1);
push(1);
push(6);
push(8);
Assert.check(min() == 1);
pop();
pop();
pop();
Assert.check(min() == 1);
pop();
Assert.check(min() == 2);
}
}