Hot100——739.每日温度

解题思路

本题的解题思路其实是需要用到单调栈。

本题中用到的是单调递减栈,那我们如何来进行使用呢?

以所给示例进行分析:

temperatures = 73, 74, 75, 71, 69, 72, 76, 73,输出应该是 1, 1, 4, 2, 1, 1, 0, 0

首先构造一个空栈(切记栈中存储的是数组元素的下标)

遍历temperatures数组,将第一个数73的下标置于栈顶,而后比较temperatures数组中每一个元素与栈顶元素的大小,

倘若当前数组元素的大小是大于当前栈顶元素的话,则不入栈,因为此时不符合递减栈的要求,需要弹出栈顶元素,直到当前数组元素是小于栈顶元素,满足单调栈的条件,此时求出相应的下标差就是对应的距离。

举例如下:

设栈为st

1.st为空,遍历temperatures数组,将数组的第一个元素的下标压入堆栈,记st0 = 0;

此时的堆栈:0

2.i=1,取temperatures1=74,74>73,此时若是压入栈则不满单调栈的条件,因此弹出栈顶元素,计算二者的下标差就是题中所求。所以res0 = 1 - 0 = 1;而后把当前数组元素的下标压入栈中。

此时的堆栈:1

3.i=2,取temperatures2=75,75>74,与2一致,弹出栈顶元素,将当前数组元素下标存入堆栈中,因此res1 = 2 - 1 = 1;

此时的堆栈:2

4.i=3,取temperatures3=71,71<75,当前数组元素大小小于栈顶元素,满足单调递减栈,存入堆栈,此时栈顶元素是3;

此时的堆栈:2 3

5.i=4,取temperatures4=69,69<71,与4一致,此时栈顶元素是4;

此时的堆栈:2 3 4

6.i=5,取temperatures5=72,72>69,与2一致,弹出当前栈顶元素,记录res4 = 5 - 4 = 1;

继续比较72 > 71,与上述一致,res3 = 5 - 3 = 2;

继续比较,72 <75,满足单调递减栈,压入堆栈,栈顶元素是5;

此时的堆栈:2 5

7.i=6,取temperatures6=76,76>72,弹出栈顶元素,res5 = 6 - 5 = 1;

继续比较76>75,弹出栈顶元素,res2 = 6 - 2 = 4;

将76存入堆栈,栈顶元素是6;

此时的堆栈:6

8.i=7,取temperatures7=73,73<76,满足单调栈,更新栈顶元素,为7。

此时的堆栈:6 7

遍历结束。

以上便是总体流程。

代码

C++

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

python

python 复制代码
class Solution(object):
    def dailyTemperatures(self, temperatures):
        """
        :type temperatures: List[int]
        :rtype: List[int]
        """
        length = len(temperatures)
        stack = []
        res = [0]*length
        for i in range(length):
            while stack and temperatures[i] > temperatures[stack[-1]]:
                t = stack.pop()
                res[t] = i - t
            stack.append(i)
        return res

参考

LeetCode 图解 | 739.每日温度

相关推荐
白狐_7986 分钟前
【408计算机网络|第04章·下|408-CN-04B】网络层(下):路由算法、RIP、OSPF、BGP、IPv6与路由器
计算机网络·算法·智能路由器
donoot1 小时前
PaddleOCR + PyMuPDF 生成【全兼容双层 PDF】完整实操指南
人工智能·算法·pymupdf·paddleocr·双层pdf
paeamecium2 小时前
【PAT甲级真题】- Rational Sum (20)
数据结构·c++·python·算法·pat考试·pat
Highcharts.js8 小时前
教程:基于 React + Highcharts 构建一个单页应用程序、按需数据拉取与图表渲染
开发语言·前端·数据结构·react.js·前端框架·highcharts·页面应用
拳里剑气11 小时前
C++算法:BFS解决FloodFill算法
c++·算法·bfs·宽度优先
wanderist.13 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
稚南城才子,乌衣巷风流13 小时前
支配树(Dominator Tree)详解:概念、算法与应用
算法
稚南城才子,乌衣巷风流14 小时前
动态开点:原理、实现与应用场景
数据结构·算法
yyds_yyd_1008614 小时前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode