|
1 | 1 | packagecom.fishercoder.solutions;
|
2 | 2 |
|
3 |
| - |
4 | 3 | importjava.util.Stack;
|
5 | 4 |
|
6 | 5 | /**
|
|
25 | 24 |
|
26 | 25 | publicclass_155 {
|
27 | 26 |
|
28 |
| -publicstaticclassMinStack { |
29 |
| -privateStack<Integer>stack; |
30 |
| -privateintmin; |
31 |
| - |
32 |
| -/** |
33 |
| - * initialize your data structure here. |
34 |
| - */ |
35 |
| -publicMinStack() { |
36 |
| -stack =newStack(); |
37 |
| -min =Integer.MAX_VALUE; |
38 |
| - } |
| 27 | +publicstaticclassSolution1 { |
| 28 | +classMinStack { |
| 29 | +privateStack<Integer>stack; |
| 30 | +privateintmin; |
39 | 31 |
|
40 |
| -publicvoidpush(intx) { |
41 |
| -/**All the trick happens here, we push the second minimum number onto the stack before we push the newer one, |
42 |
| - * this way, when popping, we could always get the next minimum one in constant time.*/ |
43 |
| -if (x <=min) { |
44 |
| -stack.push(min); |
45 |
| -min =x; |
| 32 | +/** |
| 33 | + * initialize your data structure here. |
| 34 | + */ |
| 35 | +publicMinStack() { |
| 36 | +stack =newStack(); |
| 37 | +min =Integer.MAX_VALUE; |
46 | 38 | }
|
47 |
| -stack.push(x); |
48 |
| - } |
49 | 39 |
|
50 |
| -publicvoidpop() { |
51 |
| -if (min ==stack.peek()) { |
52 |
| -stack.pop(); |
53 |
| -min =stack.pop(); |
54 |
| - }else { |
55 |
| -stack.pop(); |
| 40 | +publicvoidpush(intx) { |
| 41 | +/**All the trick happens here, we push the second minimum number onto the stack before we push the newer one, |
| 42 | + * this way, when popping, we could always get the next minimum one in constant time.*/ |
| 43 | +if (x <=min) { |
| 44 | +stack.push(min); |
| 45 | +min =x; |
| 46 | + } |
| 47 | +stack.push(x); |
56 | 48 | }
|
57 |
| -if (stack.isEmpty()) { |
58 |
| -min =Integer.MAX_VALUE; |
| 49 | + |
| 50 | +publicvoidpop() { |
| 51 | +if (min ==stack.peek()) { |
| 52 | +stack.pop(); |
| 53 | +min =stack.pop(); |
| 54 | + }else { |
| 55 | +stack.pop(); |
| 56 | + } |
| 57 | +if (stack.isEmpty()) { |
| 58 | +min =Integer.MAX_VALUE; |
| 59 | + } |
59 | 60 | }
|
60 |
| - } |
61 | 61 |
|
62 |
| -publicinttop() { |
63 |
| -returnstack.peek(); |
64 |
| - } |
| 62 | +publicinttop() { |
| 63 | +returnstack.peek(); |
| 64 | +} |
65 | 65 |
|
66 |
| -publicintgetMin() { |
67 |
| -returnmin; |
| 66 | +publicintgetMin() { |
| 67 | +returnmin; |
| 68 | + } |
68 | 69 | }
|
69 | 70 | }
|
70 |
| - |
71 | 71 | }
|