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]
.
题意:输入一个数组,代表每天的温度,求解每天需要经过几天会升温,即需找数组每个元素右边第一个比自己大的数。利用单调栈性质创建单调递减栈,遍历数组入栈,当将要入栈元素小于栈顶元素时入栈,若要入栈元素大于栈顶元素时,表示入栈元素为所求元素,记录索引,弹出栈顶元素,将此元素压栈,重新比较,一次循环时间复杂度O(n)。
样例解析:
73入栈,74>73,73出栈,74入栈,74使得73出栈,所以73需要等待1-0=1天 ,栈内元素74.
75入栈,75>74, 74出栈,75入栈,75使得74出栈,所以74需要等待2-1=1天,栈内元素75.
71入栈,71<75,直接入栈,栈内元素 75,71
69直接入栈,栈内元素75,71,69
72入栈,72>69,69出栈,72使69出栈,所以69需要等待5-4=1天,此时栈内元素75,71,由与72>71,任不满足单调栈性质,71出栈,72使71出栈,所以71需要等待5-3=2天,站内元素75,75>72,72直接入栈,栈内元素为:75,72.
以此类推。。。
代码如下:
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> s = new Stack<Integer>();
int[] res = new int[temperatures.length];
for(int i=0;i<temperatures.length;i++){
if(s.isEmpty()||temperatures[i]<temperatures[s.peek()]){
s.push(i);
}
else {
while(!s.isEmpty()&&temperatures[s.peek()]<temperatures[i]){
int index = s.pop();
res[index] = i-index;
}
s.push(i);
}
}
return res;
}
}