问题:
解题:
分析:至少需要两层,最简单就是两层for循环,也可以引入单调栈,可以去掉一些不是单调的中间值,节省遍历个数
class Solution {
/**
* public int[] dailyTemperatures(int[] temperatureArray) {
* int[] diffArray = new int[temperatureArray.length];
* int x = temperatureArray.length - 1;
* for (int i = 0; i < temperatureArray.length; i++) {
* int temperature = temperatureArray[i];
* for (int j = 1; j < temperatureArray.length - i; j++) {
* int next = temperatureArray[i + j];
* if (next > temperature) {
* diffArray[i] = j;
* break;
* }* }
* }
* diffArray[x] = 0;
* return diffArray;
* }
*/
public int[] dailyTemperatures(int[] temperatureArray) {
LinkedList<int[]> stack = new LinkedList<>();
stack.addFirst(new int[]{temperatureArray[0], 0});
for (int i = 1; i < temperatureArray.length; i++) {
while (stack.size() > 0 && stack.getFirst()[0] < temperatureArray[i]) {
int index = stack.getFirst()[1];
temperatureArray[index] = i - index;
stack.removeFirst();
}
stack.addFirst(new int[]{temperatureArray[i], i});
}
for (int[] ints : stack) {
temperatureArray[ints[1]] = 0;
}
return temperatureArray;
}
}
性能:
单调栈确实节省了很多时间