Given a list of daily temperatures T, return a list such 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 of temperatures T = [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].
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/daily-temperatures
注:leetcode中文题目我差点没看懂,应该是翻译不到位,所以还是尽量看英文吧。。
分析:很容易想到o(n^2)的解法,两个循环搞定。o(n)的方法比较巧妙,相当于记录下的之前的比较结果,节约了时间。
从右往左遍历数组,将大的数的下标保存到栈里,栈最下面的元素最大,最上面的元素离下一个要计算的位置最近。比较当前位置元素与栈顶元素对应的元素的大小,直到找到较大元素或者栈为空,然后计算需要等的天数。
class Solution {
public int[] dailyTemperatures(int[] T) {
int[] res = new int[T.length];
Stack<Integer> indexStack = new Stack<>();
for(int i = T.length - 1; i >= 0; --i) {
while(!indexStack.empty() && T[i] >= T[indexStack.peek()]) indexStack.pop();
res[i] = indexStack.empty() ? 0 : indexStack.peek() - i;
indexStack.push(i);
}
return res;
}
}