MENU

LeetCode739. Daily Temperatures(模拟 / 栈)

2019 年 04 月 16 日 • 阅读: 854 • LeetCode阅读设置

LeetCode739. Daily Temperatures(模拟 / 栈)

  • Medium
  • Accepted:57,363
  • Submissions:96,131

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 0instead.

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].


链接

https://leetcode.com/problems/daily-temperatures

题意

给定一个每天的温度列表T,求对于列表中的每一天,需要等待多少天才会有一个更高的温度。其实就相当于给定一个数组,对其中每个元素,求后面大于该元素的第一个元素的位置。

题解

  • 一种暴力的办法是两层循环,时间复杂度$O(n^2)$
  • 我们可以使用一个栈来保存还没有处理的元素下表,也就是首先第一个元素下标入栈,然后循环看后面的元素是否大于栈中元素,如果大于那么就做相应的处理,并把栈顶元素出栈,然后把当前元素下标入栈,实际上我们栈中保存的就是一个递减的“序列”下标,直到找到第一个大于栈顶元素的元素,并依次处理栈中其余元素,时间复杂度$O(n)$

代码

Time SubmittedStatusRuntimeMemoryLanguage
2 hours agoAccepted196 ms16.1 MBcpp
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        int n = T.size();
        stack <int> st;
        vector <int> res(n, 0);
        for (int i = 0; i < n; ++i)
        {
            while (!st.empty() && T[i] > T[st.top()])
            {
                res[st.top()] = i - st.top();
                st.pop();
            }
            st.push(i);
        }
        return res;
    }
};

The end.
2019年4月16日 星期二
最后编辑于: 2020 年 04 月 24 日