所谓单调栈是使用stack来保存一组单调递增或递减的数据,遇到非单调的数据则出栈。具体参加leetcode 739:每日温度。(https://leetcode-cn.com/problems/daily-temperatures/
)
算法使用单调递减栈来记录每日温度,遇到温度比栈头高的则出栈,这样就可以找到最近的比当前温度高的那一天。代码如下:
class Solution {
public int[] dailyTemperatures(int[] T) {
Stack<Integer> temp = new Stack<>();
Stack<Integer> indices = new Stack<>();
int[] res = new int[T.length];
int len = T.length;
if (len == 0) return res;
int i = 0;
while (i < len) {
while (!temp.isEmpty() && temp.peek() < T[i]) {
temp.pop();
int index = indices.pop();
res[index] = i - index;
}
temp.push(T[i]);
indices.push(i);
i++;
}
while (!indices.isEmpty()) {
int index = indices.pop();
res[index] = 0;
}
return res;
}
}
网友评论