|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
| 3 | +import java.util.Deque; |
| 4 | +import java.util.LinkedList; |
3 | 5 | import java.util.Stack;
|
4 | 6 |
|
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 |
| - |
25 | 7 | public class _155 {
|
26 | 8 |
|
27 | 9 | public static class Solution1 {
|
28 | 10 | class MinStack {
|
29 | 11 | private Stack<Integer> stack;
|
30 | 12 | private int min;
|
31 | 13 |
|
32 |
| - /** |
33 |
| - * initialize your data structure here. |
34 |
| - */ |
35 | 14 | public MinStack() {
|
36 | 15 | stack = new Stack();
|
37 | 16 | min = Integer.MAX_VALUE;
|
@@ -64,4 +43,45 @@ public int getMin() {
|
64 | 43 | }
|
65 | 44 | }
|
66 | 45 | }
|
| 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 | + } |
67 | 87 | }
|
0 commit comments