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次温度表,找出符合条件的天数。
复杂度为O(n^2) 超时
class Solution { public: vector<int> dailyTemperatures(vector<int>& temperatures) { vector<int> res(temperatures.size(), 0); for (int i = 0; i < temperatures.size(); i++) { for (int j = i + 1; j < temperatures.size(); j++) { if (temperatures[j] - temperatures[i] > 0) { res[i] = j - i; break; } } } return res; } }; // TLE
思路2:使用一个stack来存储待比较的元素,直到遇到符合条件的值后再一一出栈比较。只需要遍历一次温度表。
class Solution { public: vector<int> dailyTemperatures(vector<int>& temperatures) { vector<int> res(temperatures.size(), 0); stack<pair<int, int>> stk; for (int i = 0; i < temperatures.size(); i++) { while (!stk.empty() && temperatures[i] > stk.top().first) { res[stk.top().second] = i - stk.top().second; stk.pop(); } stk.push(make_pair(temperatures[i], i)); } return res; } }; // 233 ms