-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMinStack.java
More file actions
72 lines (59 loc) · 1.5 KB
/
MinStack.java
File metadata and controls
72 lines (59 loc) · 1.5 KB
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
/**
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
Note that all the operations have to be constant time operations.
Questions to ask the interviewer :
Q: What should getMin() do on empty stack?
A: In this case, return -1.
Q: What should pop do on empty stack?
A: In this case, nothing.
Q: What should top() do on empty stack?
A: In this case, return -1
**/
class Solution {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
stack.push(x);
if(minStack.isEmpty())
{
minStack.push(x);
}
else
{
if(minStack.peek() > x)
{
minStack.push(x);
}
else
{
minStack.push(minStack.peek());
}
}
}
public void pop() {
if(stack.isEmpty())
{
return;
}
stack.pop();
minStack.pop();
}
public int top() {
if(stack.isEmpty())
{
return -1;
}
return stack.peek();
}
public int getMin() {
if(minStack.isEmpty())
{
return -1;
}
return minStack.peek();
}
}