Skip to content

Commit c920110

Browse files
add min stack
1 parent 8ef7a24 commit c920110

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

EASY/src/easy/MinStack.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package easy;
2+
3+
import java.util.*;
4+
5+
public class MinStack {
6+
7+
private Stack<Integer> stack;
8+
private int min;
9+
10+
/** initialize your data structure here. */
11+
public MinStack() {
12+
stack = new Stack();
13+
min = Integer.MAX_VALUE;
14+
}
15+
16+
public void push(int x) {
17+
/**All the trick happens here, we push the second minimum number onto the stack before we push the newer one,
18+
* this way, when popping, we could always get the next minimum one in constant time.*/
19+
if(x <= min){
20+
stack.push(min);
21+
min = x;
22+
}
23+
stack.push(x);
24+
}
25+
26+
public void pop() {
27+
if(min == stack.peek()){
28+
stack.pop();
29+
min = stack.pop();
30+
} else {
31+
stack.pop();
32+
}
33+
if(stack.isEmpty()) min = Integer.MAX_VALUE;
34+
}
35+
36+
public int top() {
37+
return stack.peek();
38+
}
39+
40+
public int getMin() {
41+
return min;
42+
}
43+
44+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
|173|[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/)|[Queue](../../blob/master/MEDIUM/src/medium/BSTIterator_using_q.java) [Stack](../../blob/master/MEDIUM/src/medium/BSTIterator_using_stack.java)| O(1) |O(h) | Medium|
2828
|172|[Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/)|[Solution](../../blob/master/EASY/src/easy/FactorialTrailingZeroes.java)| O(logn)|O(1)| Easy
2929
|162|[Find Peak Element](https://leetcode.com/problems/find-peak-element/)|[Solution](../../blob/master/MEDIUM/src/medium/FindPeakElement.java) | O(1) |O(logn)/O(n) | Binary Search|
30+
|155|[Min Stack](https://leetcode.com/problems/min-stack/)|[Solution](../../blob/master/EASY/src/easy/MinStack.java)| O(1)|O(n) | Easy| Stack
3031
|140|[Word Break II](https://leetcode.com/problems/word-break-ii/)|[Solution](../../blob/master/HARD/src/hard/WordBreakII.java)| ? |O(n^2) | Hard| Backtracking/DFS
3132
|139|[Word Break](https://leetcode.com/problems/word-break/)|[Solution](../../blob/master/MEDIUM/src/medium/WordBreak.java)| O(n^2)|O(n) | Medium| DP
3233
|133|[Clone Graph](https://leetcode.com/problems/clone-graph/)|[Solution](../../blob/master/MEDIUM/src/medium/CloneGraph.java)| O(n)|O(n) | Medium| HashMap, BFS

0 commit comments

Comments
 (0)