155. Min Stack

https://leetcode.com/problems/min-stack/

Approach 1: Stack of Value/ Minimum Pairs

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
class MinStack {
class Node{
int val;
int currMin;
Node(int val,int currMin){this.val=val;this.currMin=currMin;}
}

LinkedList<Node> stack;
/** initialize your data structure here. */
public MinStack() {
stack=new LinkedList<>();
}

public void push(int x) {
if(stack.isEmpty()) {
stack.push(new Node(x,x));
}else{
int preMin=stack.peek().currMin;
stack.push(new Node(x,Math.min(x,preMin)));
}
}

public void pop() {
stack.pop();
}

public int top() {
return stack.peek().val;
}

public int getMin() {
return stack.peek().currMin;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/

Approach 2: Two Stacks

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
class MinStack {
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> minStack = new Stack<>();

public MinStack() { }

public void push(int x) {
stack.push(x);
if (minStack.isEmpty() || x <= minStack.peek()) {
minStack.push(x);
}
}

public void pop() {
if (stack.peek().equals(minStack.peek())) {
minStack.pop();
}
stack.pop();
}

public int top() {
return stack.peek();
}

public int getMin() {
return minStack.peek();
}
}

Approach 3: Improved Two Stacks

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
class MinStack {

private Stack<Integer> stack = new Stack<>();
private Stack<int[]> minStack = new Stack<>();

public MinStack() {
}

public void push(int x) {

// We always put the number onto the main stack.
stack.push(x);

// If the min stack is empty, or this number is smaller than
// the top of the min stack, put it on with a count of 1.
if (minStack.isEmpty() || x < minStack.peek()[0]) {
minStack.push(new int[] { x, 1 });
}
// Else if this number is equal to what's currently at the top
// of the min stack, then increment the count at the top by 1.
else if (x == minStack.peek()[0]) {
minStack.peek()[1]++;
}
}

public void pop() {

// If the top of min stack is the same as the top of stack
// then we need to decrement the count at the top by 1.
if (stack.peek().equals(minStack.peek()[0])) {
minStack.peek()[1]--;
}

// If the count at the top of min stack is now 0, then remove
// that value as we're done with it.
if (minStack.peek()[1] == 0) {
minStack.pop();
}

// And like before, pop the top of the main stack.
stack.pop();
}

public int top() {
return stack.peek();
}

public int getMin() {
return minStack.peek()[0];
}
}

0%