Daily Temperatures单调栈--力扣101算法题解笔记

11.4Daily Temperatures单调栈

题目描述

给定每天的温度,求对于每一天需要等几天才可以等到更暖和的一天,如果该天之后不存在更暖和的天气,则记为0。

输入输出样例

Input :{73, 74, 75, 71, 69, 72, 76, 73}

Output:[1, 1, 4, 2, 1, 1, 0, 0]

题解

我们可以维持一个单调递减的栈,表示每天的温度;为了方便计算天数差,我们这里存放位置(即日期)而非温度本身。我们从左向右遍历温度数组,对于每个日期 p,如果 p 的温度比栈顶存储位置 q 的温度高,则我们取出 q,并记录 q 需要等待的天数为 p - q;我们重复这一过程,直到 p 的温度小于等于栈顶存储位置的温度(或空栈)时,我们将 p 插入栈顶,然后考虑下一天。在这个过程中,栈内数组永远保持单调递减,避免了使用排序进行比较。最后若栈内剩余一些日期,则说明它们之后都没有出现更暖和的日期。

cpp 复制代码
#include <iostream>
#include <vector>
#include <stack>

using namespace std;

// 核心算法函数
vector<int> dailyTemperatures(vector<int>& temperatures) {
    int n = temperatures.size();
    vector<int> ans(n, 0); // 初始化为0,这样栈中剩余的元素自动对应结果0
    stack<int> indices;    // 单调栈,存储下标

    for (int i = 0; i < n; ++i) {
        // 当栈不为空,且当前温度高于栈顶下标对应的温度时
        while (!indices.empty() && 
            temperatures[i] > temperatures[indices.top()]) {
            int pre_index = indices.top();
            indices.pop();
            ans[pre_index] = i - pre_index; // 计算天数差
        }
        indices.push(i); // 将当前下标压入栈
    }
    return ans;
}

// 辅助函数:打印向量
void printVector(const vector<int>& vec) {
    cout << "[";
    for (size_t i = 0; i < vec.size(); ++i) {
        cout << vec[i];
        if (i != vec.size() - 1) {
            cout << ", ";
        }
    }
    cout << "]" << endl;
}

int main() {
    // 定义输入数据
    vector<int> temperatures = { 73, 74, 75, 71, 69, 72, 76, 73 };

    cout << "Input:  {73, 74, 75, 71, 69, 72, 76, 73}" << endl;

    // 调用函数
    vector<int> result = dailyTemperatures(temperatures);

    // 输出结果
    cout << "Output: ";
    printVector(result);

    return 0;
}
相关推荐
炽烈小老头2 小时前
【每天学习一点算法 2026/03/21】颜色分类
学习·算法
qyzm2 小时前
天梯赛练习题
数据结构·python·算法·贪心算法
灰色小旋风2 小时前
力扣17 电话号码的字母组合(C++)
c++·算法·leetcode
无敌憨憨大王2 小时前
并查集(图论)
数据结构·算法·图论
xiaoye-duck2 小时前
《算法题讲解指南:动态规划算法--路径问题》--7.礼物的最大价值,8.下降路径最小和
c++·算法·动态规划
光影少年2 小时前
react的diff算法和vue的diff算法区别
vue.js·算法·react.js
Queenie_Charlie2 小时前
二分匹配
c++·算法·二分匹配
历程里程碑2 小时前
链表--排序链表
大数据·数据结构·算法·elasticsearch·链表·搜索引擎·排序算法
IT猿手2 小时前
基于动态三维环境下的Q-Learning算法无人机自主避障路径规划研究,MATLAB代码
算法·matlab·无人机·动态路径规划·多无人机动态避障路径规划