玩命加载中 . . .

739-每日温度


LeetCode 739. Daily Temperatures

LeetCode-739

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;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录