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;
}
相关推荐
灵感__idea5 小时前
Hello 算法:贪心的世界
前端·javascript·算法
澈2076 小时前
深入浅出C++滑动窗口算法:原理、实现与实战应用详解
数据结构·c++·算法
ambition202426 小时前
从暴力搜索到理论最优:一道任务调度问题的完整算法演进历程
c语言·数据结构·c++·算法·贪心算法·深度优先
cmpxr_6 小时前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法
qiqsevenqiqiqiqi6 小时前
前缀和差分
算法·图论
代码旅人ing6 小时前
链表算法刷题指南
数据结构·算法·链表
Yungoal7 小时前
常见 时间复杂度计算
c++·算法
不爱吃炸鸡柳8 小时前
单链表专题(完整代码版)
数据结构·算法·链表
CylMK8 小时前
题解:AT_abc382_d [ABC382D] Keep Distance
算法
Dfreedom.8 小时前
计算机视觉全景图
人工智能·算法·计算机视觉·图像算法