LeetCode 739. Daily Temperatures
Given a list of daily temperatures temperatures, 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 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].
单调栈模板
method: 单调栈
从栈底到栈顶的下标在数组
arr
中对应的值是单调递减(不增)的
从前往后遍历,如果比栈顶元素小,就入栈,否则一直把栈顶元素弹出,直到栈空或者可以入栈为止。
入栈的是数组的下标,因为可以用下标找元素,但不能用元素找下标
vector<int> dailyTemperatures(vector<int>& arr) {
stack<int> st;
vector<int> ret(arr.size());
for (int i = 0; i < arr.size(); ++i) {
while (!st.empty() && arr[i] > arr[st.top()]) {
ret[st.top()] = i - st.top(); // 下标的差值
st.pop();
}
st.push(i);
}
return ret;
}