题目:
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]
.
思路:
我们定义一个栈,然后在遍历温度的时候分别做如下处理:
1)如果当天的温度比第二天的温度高,那么我们暂时还无法确定需要等多少天才能有更高的温度,所以就将当天的温度入栈。
2)如果当天的温度比第二天的温度低,那么它需要等待的天数就是1。但是此时我们需要更新栈顶元素对应的那天的等待时间。我们以题目中给出的例子为例来讲解:[73, 74, 75, 71, 69, 72, 76, 73]。扫描73, 74的时候,其对应结果为1;当遇到75的时候,由于75 > 71,所以我们将75入栈(此时栈内元素为75),71也同理(此时栈内元素为75,71)。当遇到69的时候,69 < 72,所以69的对应结果为1,但是由于72大于栈顶元素71,所以此时可以修改71对应的等待天数,即为72对应的天数索引与71对应的天数索引,然后71出栈(此时栈内元素为75);当处理72的时候,结果为1,但是由于76大于栈顶元素75,所以修改75的等待天数,并出栈(此时栈内为空)。当处理76的时候,76需入栈。由于再也没有比76大的元素,并且73之后也没有元素了,所以76,73对应的等待天数就都为0了,在程序中并没有做处理。
算法的空间复杂度为O(n),时间复杂度也为O(n),这是因为for循环里面的while循环中,每个元素最多出一次栈,所以while总的执行次数是O(n)量级的。
代码:
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> ret(n, 0);
stack<pair<int, int>> s;
for (int i = 0; i < n - 1; ++i) {
if (temperatures[i] < temperatures[i + 1]){
ret[i] = 1;
while (!s.empty() && temperatures[i + 1] > s.top().first) {
ret[s.top().second] = i + 1 - s.top().second;
s.pop();
}
}
else {
s.push(make_pair(temperatures[i], i));
}
}
return ret;
}
};