单调栈
求左边/右边第一个比当前数小的值->单调递增栈。求左边/右边第一个比当前数大的值->单调递减栈
Min Stack
class MinStack {
Stack<Integer> stk, minStk;
/** initialize your data structure here. */
public MinStack() {
stk = new Stack<>();
minStk = new Stack<>();
}
public void push(int x) {
stk.push(x);
if (minStk.isEmpty() || minStk.peek() >= x) {
minStk.push(x);
}
}
public void pop() {
int val = stk.pop();
if (minStk.peek() == val) {
minStk.pop();
}
}
public int top() {
return stk.peek();
}
public int getMin() {
return minStk.peek();
}
}Max Stack
Largest Rectangle in Histogram
Next greater element类问题,经典的单调栈应用
Next Greater Element I
Next Greater Element II
Next Greater Node in Linked List
Last updated