[LeetCode] Daily Temperatures 日常温度

简介: 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.

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

这道题给了我们一个数组,让我们找下一个比当前数字大的数字的距离,我们研究一下题目中给的例子,发现数组是无序的,所以没法用二分法快速定位下一个大的数字,那么最先考虑的方法就是暴力搜索了,写起来没有什么难度,但是OJ并不答应。实际上这道题应该使用递减栈Descending Stack来做,栈里只有递减元素,思路是这样的,我们遍历数组,如果栈不空,且当前数字大于栈顶元素,那么如果直接入栈的话就不是递减栈了,所以我们取出栈顶元素,那么由于当前数字大于栈顶元素的数字,而且一定是第一个大于栈顶元素的数,那么我们直接求出下标差就是二者的距离了,然后继续看新的栈顶元素,直到当前数字小于等于栈顶元素停止,然后将数字入栈,这样就可以一直保持递减栈,且每个数字和第一个大于它的数的距离也可以算出来了,参见代码如下: 


class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        vector<int> res(n, 0);
        stack<int> st;
        for (int i = 0; i < temperatures.size(); ++i) {
            while (!st.empty() && temperatures[i] > temperatures[st.top()]) {
                auto t = st.top(); st.pop();
                res[t] = i - t;
            }
            st.push(i);
        }
        return res;
    }
};

  

参考资料:

https://discuss.leetcode.com/topic/112830/java-easy-ac-solution-with-stack

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Daily Temperatures 日常温度

,如需转载请自行联系原博主。

相关文章
|
7天前
|
算法
代码随想录算法训练营第五十七天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
代码随想录算法训练营第五十七天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
11 3
|
3月前
|
容器
代码随想录 Day49 单调栈01 LeetCode LeetCodeT739每日温度 T496 下一个最大元素I
代码随想录 Day49 单调栈01 LeetCode LeetCodeT739每日温度 T496 下一个最大元素I
32 0
|
3月前
|
SQL
leetcode-SQL-197. 上升的温度
leetcode-SQL-197. 上升的温度
15 0
|
3月前
|
索引
leetcode-739:每日温度
leetcode-739:每日温度
22 0
【LeetCode-每日一题】-739-每日温度
【LeetCode-每日一题】-739-每日温度
|
测试技术 数据库
LeetCode(数据库)- 上升的温度
LeetCode(数据库)- 上升的温度
112 0
|
存储
LeetCode 739. 每日温度
LeetCode 739. 每日温度
65 0
LeetCode 739. 每日温度
|
前端开发 算法 JavaScript
LeetCode每日温度问题使用JavaScript解题|前端学算法
LeetCode每日温度问题使用JavaScript解题|前端学算法
109 0
LeetCode每日温度问题使用JavaScript解题|前端学算法
代码随想录刷题|LeetCode 739. 每日温度 496.下一个更大元素 I
代码随想录刷题|LeetCode 739. 每日温度 496.下一个更大元素 I