-
Notifications
You must be signed in to change notification settings - Fork 5
/
MinStack.java
57 lines (47 loc) · 1.35 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
/*
Problem Statement:
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.
Problem Link:
Min Stack: https://leetcode.com/problems/min-stack/description/
Solution:
https://github.com/sunnypatel165/leetcode-again/blob/master/solutions/MinStack.java
Author:
Sunny Patel
https://github.com/sunnypatel165
https://www.linkedin.com/in/sunnypatel165/
*/
class MinStack {
Stack minStack = new Stack();
Stack stack = new Stack();
public MinStack() {
minStack = new Stack();
}
public void push(int x) {
stack.push(x);
if(minStack.empty() || x < (int)minStack.peek())
minStack.push(x);
else
minStack.push((int)minStack.peek());
}
public void pop() {
if(!stack.isEmpty())
stack.pop();
if(!minStack.isEmpty())
minStack.pop();
}
public int top() {
if(stack.isEmpty())
return 0;
return (int)stack.peek();
}
public int getMin() {
if(minStack.isEmpty())
return 0;
return (int)minStack.peek();
}
}