请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
解题思路:
单调栈思路,遇到比你大的你就应该弹栈,算出几天后天气变高,比你小的就压栈,栈内元素维持单调递减。
class Solution { public int[] dailyTemperatures(int[] T) { // 这里使用双向队列速度提升很大,很迷幻。 Deque<Integer> stack = new LinkedList<Integer>(); int[] res = new int[T.length]; // 单调递增的队列,从后往前走 for(int i = T.length - 1; i >= 0; i--) { while(!stack.isEmpty() && T[i] >= T[stack.peek()]) { int idx = stack.pop(); if(stack.isEmpty()) { res[idx] = 0; } else { res[idx] = stack.peek() - idx; } } stack.push(i); } while(!stack.isEmpty()) { int idx = stack.pop(); if(stack.isEmpty()) { res[idx] = 0; } else { res[idx] = stack.peek() - idx; } } return res; } } // 官方题解,正向走,方法很清晰 class Solution { public int[] dailyTemperatures(int[] T) { // 这里一定要使用双向队列,否则速度不是很快 Deque<Integer> stack = new LinkedList<Integer>(); int[] res = new int[T.length]; for(int i = 0; i < T.length; ++i){ while(!stack.isEmpty() && T[i] > T[stack.peek()]){ int temp = stack.pop(); res[temp] = i - temp; } stack.push(i); } return res; } }
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/daily-temperatures 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
原文:https://www.cnblogs.com/PHUN19/p/13378842.html