单调栈:
保持栈内的元素始终递增或递减。
单调递增 待处理数组{1,5,2,5,7,2,8}
public void sameyIncrease(int[] nums) {
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < nums.length; i++) {
//当栈空的时候可以直接进栈或者要进栈的数大于等于栈顶的数
if(stack.isEmpty() || nums[stack.peek()] <= nums[i]) {
stack.push(i);
} else {
//当进栈的数不满足规律的时候我们将原本栈内的数弹出,直至满足规律或栈空了
while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]) {
stack.pop();
}
stack.push(i);
}
}
}
单调递减 待处理数组{1,5,2,5,7,2,8}
public void sameyIncrease(int[] nums) {
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < nums.length; i++) {
if(stack.isEmpty() || nums[stack.peek()] >= nums[i]) {
stack.push(i);
} else {
while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]) {
stack.pop();
}
stack.push(i);
}
}
}