单调栈
求左边/右边第一个比当前数小的值->单调递增栈。求左边/右边第一个比当前数大的值->单调递减栈
Min Stack
brute force solution
建立两个stack,
stkandminStk,两个存相同数量的数(空间不是最优)每次stk.pop()之后都call minStk.pop()
stk.push()的时候判断cur和minStk.peek()的大小
improve solution
minStk不用每次都更新,只需要当push出现更小值的时候再push
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
brute force solution---Interview friendly
3 stacks,
stk,maxStkandbufferinside of popMax()size of
stkandmaxStkis always same
Optimize to not use maxStk, use a
maxvariable instead
Largest Rectangle in Histogram
如何构成rectangle
given index i, 找到i左边的第一个小于nums[i]的值,右边的第一个小于nums[i]的值
因此想到单调递增栈
每次curHeight和heights[stk.peek()]比较,如果比heights[stk.peek()]小的话,height[stk.pop()]就是height, curHeight就是右边界, 更新的栈里的stk.peek()就是左边界
Next greater element类问题,经典的单调栈应用
Next greater element I
Next greater element II
Next greater node in Linked List
Daily Temperature
Next Greater Element I
给两个数组,nums1和nums2, nums1 是nums2 的子集
要求返回nums1里每一个数在nums2里的next greater element
典型的单调栈问题
从右向左遍历nums2, 维护单调递减栈
always compare nums2[i] with stk.peek()
if nums[i] < stk.peek() then arr[i] == stk.peek()
else stk.pop(), try again until stk.isEmpty()
原始版本代码
优化后的clean code
Next Greater Element II
给定一个nums, 求nums里每一个数的next greater element
nums is circular array
跟第一题相同的思路,但是需要iterate 2 loops, i from 2 * n - 1 to 0
Next Greater Node in Linked List
首先convert linked list to array, 然后就是典型的find next greater element的问题
求右边第一个比当前数大的值->单调递减栈
follow up: 求左边第一个比当前数大的值, previous greater element 也是单调递减栈
Last updated
Was this helpful?