File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change 27
27
| 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|
28
28
|172|[ Factorial Trailing Zeroes] ( https://leetcode.com/problems/factorial-trailing-zeroes/ ) |[ Solution] ( ../../blob/master/EASY/src/easy/FactorialTrailingZeroes.java ) | O(logn)|O(1)| Easy
29
29
| 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
30
31
|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
31
32
|139|[ Word Break] ( https://leetcode.com/problems/word-break/ ) |[ Solution] ( ../../blob/master/MEDIUM/src/medium/WordBreak.java ) | O(n^2)|O(n) | Medium| DP
32
33
|133|[ Clone Graph] ( https://leetcode.com/problems/clone-graph/ ) |[ Solution] ( ../../blob/master/MEDIUM/src/medium/CloneGraph.java ) | O(n)|O(n) | Medium| HashMap, BFS
You can’t perform that action at this time.
0 commit comments