Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的都是 [30, 100] 范围内的整数。
题解:这题是可以和LeetCode中的栈一类题中的nextGreaterElement I这道题类似,基本是一样的。都是通过一个Stack+hashMap来实现,其中stack放的是原来数组元素,然后逐渐遍历,当发现数组中第一个比之前的其他元素都要大的元素后,就将当前栈的栈顶元素压出栈,然后将key作为当前数组中即温度,将value作为第一个比当前温度高的温度的下标,用于后续计算两个下标之间的差值。
public int[] dailyTemperatures(int[] temperatures)
{
int n = temperatures.length;
int[] ans = new int[n];
Stack<Integer> stack = new Stack<>();
Map<Integer, Integer> mem = new HashMap<>();
for (int i = 0; i < n; ++i) //用于扫描温度数组
{
while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i])
{ //栈用来保存还没有找到比该温度大的温度,当找到栈顶温度比该温度要大时,就
//将该元素压出栈,同时将该温度及第一个比该温度要大的位置保存在HashMap中
int nxt = stack.pop();
mem.put(nxt, i);
}
stack.push(i);
}
for (int i = 0; i < n; ++i) //最后再次遍历一遍,寻找保存在hashMap中的元素,如果存在
//某个Key,那么意味着存在比该key要大的元素,那么直接计算
//相关的差即可。
{
if (mem.containsKey(i))
{
ans[i] = mem.get(i) - i;
}
else ans[i] = 0;
}
return ans;
}
这道题与后面的nextGreaterElement I雷同,都是一个思路,且相同的做法。一模一样,这两题都可以一起来进行对比。
博客围绕根据每日气温列表生成需等待多久温度升高的天数列表问题展开。给出示例,还提示了列表长度和气温值范围。题解指出该题与LeetCode中nextGreaterElement I类似,通过Stack + hashMap实现,可将两题对比学习。
846

被折叠的 条评论
为什么被折叠?



