Skip to content

Commit 4c640c0

Browse files
add a solution for 155
1 parent 7a7e795 commit 4c640c0

File tree

1 file changed

+43
-23
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+43
-23
lines changed

src/main/java/com/fishercoder/solutions/_155.java

+43-23
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,16 @@
11
package com.fishercoder.solutions;
22

3+
import java.util.Deque;
4+
import java.util.LinkedList;
35
import java.util.Stack;
46

5-
/**
6-
* 155. Min Stack
7-
* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
8-
9-
* push(x) -- Push element x onto stack.
10-
* pop() -- Removes the element on top of the stack.
11-
* top() -- Get the top element.
12-
* getMin() -- Retrieve the minimum element in the stack.
13-
14-
* Example:
15-
* MinStack minStack = new MinStack();
16-
* minStack.push(-2);
17-
* minStack.push(0);
18-
* minStack.push(-3);
19-
* minStack.getMin(); --> Returns -3.
20-
* minStack.pop();
21-
* minStack.top(); --> Returns 0.
22-
* minStack.getMin(); --> Returns -2.
23-
*/
24-
257
public class _155 {
268

279
public static class Solution1 {
2810
class MinStack {
2911
private Stack<Integer> stack;
3012
private int min;
3113

32-
/**
33-
* initialize your data structure here.
34-
*/
3514
public MinStack() {
3615
stack = new Stack();
3716
min = Integer.MAX_VALUE;
@@ -64,4 +43,45 @@ public int getMin() {
6443
}
6544
}
6645
}
46+
47+
public static class Solution2 {
48+
/**
49+
* We could store a pair onto the stack: the first element in the pair is the value itself,
50+
* the second element in the pair is the current minimum element so far seen on the stack.
51+
*/
52+
class MinStack {
53+
Deque<int[]> stack;
54+
55+
public MinStack() {
56+
stack = new LinkedList<>();
57+
}
58+
59+
public void push(int val) {
60+
if (!stack.isEmpty()) {
61+
int[] last = stack.peekLast();
62+
int currentMin = last[1];
63+
if (val < currentMin) {
64+
stack.addLast(new int[]{val, val});
65+
} else {
66+
stack.addLast(new int[]{val, currentMin});
67+
}
68+
} else {
69+
stack.addLast(new int[]{val, val});
70+
}
71+
}
72+
73+
public void pop() {
74+
stack.pollLast();
75+
}
76+
77+
public int top() {
78+
return stack.peekLast()[0];
79+
}
80+
81+
public int getMin() {
82+
return stack.peekLast()[1];
83+
}
84+
}
85+
86+
}
6787
}

0 commit comments

Comments
 (0)