Problem: 155. 最小栈
文章目录
- 思路
- 💖 Stack + 自定义 Node
- 🍻 Code
思路
👩🏫 甜姨
💖 Stack + 自定义 Node
时间复杂度: O ( 1 ) O(1) O(1)
空间复杂度: O ( n ) O(n) O(n)
🍻 Code
class MinStack {private Stack<Node> stack;class Node{int x;int min;public Node(int x, int min){super();this.x = x;this.min = min;}}public MinStack(){stack = new Stack<>();}public void push(int x){if (stack.isEmpty())stack.add(new Node(x, x));elsestack.add(new Node(x, Math.min(x, stack.peek().min)));}public void pop(){stack.pop();}public int top(){return stack.peek().x;}public int getMin(){return stack.peek().min;}
}/*** Your MinStack object will be instantiated and called as such:* MinStack obj = new MinStack();* obj.push(val);* obj.pop();* int param_3 = obj.top();* int param_4 = obj.getMin();*/