1.什么是单调栈?
就是一个栈,只是使用了一点巧妙的逻辑,使得每次新元素加入后,栈内的元素保持单调。
496. 下一个更大元素 I
1.题目分析
- 1.先把nums2数组对应元素的最大值求出来,再处理nums1数组。
- 使用单调栈,从前向后,把没有找到比自己大的数入栈,直到找到一个数比栈顶的数大,把栈顶出栈,再比较新栈顶是否依然比当前元素大?
- 是,则出栈;
- 不是,则向下遍历。
- 2.再对nums1遍历,把符合条件的存入新数组。
2.代码
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Stack<Integer> stack = new Stack<>();
Map<Integer,Integer> map = new HashMap<>();
int len2 = nums2.length;
for (int i = 0; i < len2; i++) {
为所有比当前nums2[i]小的数 保存值
while (!stack.isEmpty() && stack.peek() < nums2[i]){
map.put(stack.pop(),nums2[i]);
}
stack.push(nums2[i]);
}
int[] ans1 = new int[nums1.length];
for (int i = 0; i < ans1.length; i++) {
ans1[i] = map.getOrDefault(nums1[i],-1);
}
return ans1;
}
}
剑指 Offer II 038. 每日温度
1.题目分析——单调栈思路
- 1.新建数据结构,tenpInd,存储温度 及 数组下标;
- 2.Stack中的元素,是按温度非升序排列的;
- 3.当遇到比栈顶元素大的元素时,进行出栈操作,并保存相差天数到res数组。
2.代码
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int len = temperatures.length;
int[] res = new int[len];
新建数据结构:存储温度及其下标
tempInd[] tempInds = new tempInd[len];
存到栈内的元素 是单调递减的
Stack<tempInd> stack = new Stack<>();
for (int i = 0; i < len; i++) {
tempInds[i] = new tempInd(temperatures[i], i);
}
从前向后遍历
for (int i = 0; i < len; i++) {
当遇到某一天的温度比之前的高,则进行出栈操作
while (!stack.isEmpty() && temperatures[i] > stack.peek().temp){
tempInd temp = stack.pop();
当前的下标 与 出栈元素成员变量index 之差即为天数
res[temp.index] = i - temp.index;
}
stack.push(tempInds[i]);
}
return res;
}
public class tempInd{
int temp;
int index;
public tempInd() {
}
public tempInd(int temp, int index) {
this.temp = temp;
this.index = index;
}
}
}
503. 下一个更大元素 II——循环数组
1.题目分析
- 相较于不是循环数组的,可以想象着把数组扩大一倍。就可以了。
- for循环时,取nums[i%len]即可。
- 从后向前遍历,维护一个单调递减的栈;
2.代码
class Solution {
public int[] nextGreaterElements(int[] nums) {
Stack<Integer> stack = new Stack<>();
int len = nums.length;
int[] res = new int[len];
1.从后向前遍历,维护一个单调递减的栈;
for (int i = len*2-1; i >= 0; i--) {
2.栈顶元素比当前元素小,就出栈
while (!stack.isEmpty() && stack.peek() <= nums[i%len]) {
stack.pop();
}
3.更新右侧最大值
res[i%len] = stack.isEmpty() ? -1 : stack.peek();
4.入栈
stack.push(nums[i%len]);
}
return res;
}
}
402. 数字串String,移掉 K 位数字求最小的数字
题目分析——单调栈+贪心算法
- 单调栈保证让小的数字尽可能靠前,
- eg:21537,若k=2,要把1前边的2给删掉、3前边的5给删掉
class Solution {
public String removeKdigits(String num, int k) {
if (num==null || num.length()==k)
return "0";
1.单调栈 :以21537 为例
尽量让1之前的2去掉,让3之前的5去掉 越小的字符在前,那整个数也越小
Stack<Character> stack = new Stack<>();
for (int i = 0; i < num.length(); i++) {
2. k要大于0,删除的字符个数不能大于k 2.栈不能为 空 3.栈顶元素要大于当前位置的 字符
满足这3个条件,则为了维护单调栈需要出栈
while (k!=0 && !stack.isEmpty() && stack.peek() > num.charAt(i)){
stack.pop();
k--; 删除数量 -1
}
stack.push(num.charAt(i));
}
3.保证k个字符都删除完
while (k!=0){
stack.pop();
k--;
}
4.拼接字符串
StringBuffer sb = new StringBuffer();
while (!stack.isEmpty()){
sb.append(stack.pop());
}
5.高位不能以0打头, 这里字符串还是反的,所以从后边删
sb.length()>1 是考虑到,单个 0 是可以的,否则把这个0也删了,就成空串了
while (sb.length()>1 && sb.charAt(sb.length()-1)=='0'){
sb.deleteCharAt(sb.length()-1);
}
6.做个反转
return sb.reverse().toString();
}
}