- 题目:
Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
* push(x) — Push element x onto stack.
* pop() — Removes the element on top of the stack.
* top() — Get the top element.
* getMin() — Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); —> Returns -3.
minStack.pop();
minStack.top(); —> Returns 0.
minStack.getMin(); —> Returns -2.
提示:提交代码后,需要用简洁的语言解释一下代码思路~ 谢谢
历史题目和总结见公众号「每日一道算法题」
https://leetcode.com/problems/min-stack/#/description
-
解决思路:
- 主类:
public class TestStack {
private Node top;
private Integer min;
public TestStack() {
}
public void push(int x) {
min = (min == null || min > x) ? x : min;
if (top == null) {
top = new Node(x);
} else {
Node node = new Node(x);
node.next = top;
top = node;
}
}
public void pop() {
if (top != null) {
int index = top.index;
top = top.next;
if (index == min) {
min = findMin();
}
} else {
throw new StackOverflowError();
}
}
public int top() {
if (top != null) {
return top.index;
} else {
throw new StackOverflowError();
}
}
public int getMin() {
return min;
}
private Integer findMin() {
if (top != null) {
min = top.index;
Node next = top.next;
while (next != null) {
Node node = next;
if (min > node.index) {
min = node.index;
}
next = node.next;
}
} else {
min = null;
}
return min;
}
public static class Node {
private int index;
private Node next;
public Node(int index) {
this.index = index;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (top != null) {
builder.append(top.index).append(",");
Node next = top.next;
while (next != null) {
Node node = next;
builder.append(node.index).append(",");
next = node.next;
}
}
return builder.toString();
}
}
- 测试类:
public class Test {
public static void main(String[] args) {
MinStack minStack = new MinStack<>();
minStack.push(2147483646);
minStack.push(2147483646);
minStack.push(2147483647);
minStack.top();
minStack.pop();
minStack.getMin();
minStack.pop();
minStack.getMin();
minStack.pop();
minStack.push(2147483647);
int min = minStack.getMin();
System.out.println("minStack min=" + min);
}
}
-
算法说明:
- Java中,实现栈操作的位Dqueue接口,但是这里我并没有直接拿来用,而是按照LinkList的
链表
来实现的,每个元素都是一个Node
;并且每个元素都有向下的引用,具体结构如下,这也是链表的基本实现原理,即每个元素都持有身边两个元素的引用,使得想很多个孩子一样,手拉手...
- Java中,实现栈操作的位Dqueue接口,但是这里我并没有直接拿来用,而是按照LinkList的
image.png
image.png
- 为了得到最大的程序效率,在push和pop的过程中,对最小值进行缓存处理,提高程序的响应速度;