【LeetCode】【算法】739. 每日温度

LeetCode 739. 每日温度

题目描述

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

示例:

输入: temperatures = [73,74,75,71,69,72,76,73]

输出: [1,1,4,2,1,1,0,0]

思路

思路:单调栈,栈中存储的是一个数组,包括当日温度和天数

  1. 遍历温度数组,逐步将温度压入栈中;
  2. 当遇到下一个高温(temperatures[i] > deque.peek()[0])时,使用while循环弹出结果,并将当前温度压入数组

代码

java 复制代码
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Deque<Integer[]> deque = new ArrayDeque<>();
        int[] result = new int[temperatures.length];
        for (int i = 0; i < temperatures.length; i++) {
            if (!deque.isEmpty() && deque.getLast()[0] < temperatures[i]){ // 说明出现了下一个大温度
                while (!deque.isEmpty() && deque.getLast()[0] < temperatures[i]){
                    Integer[] popElem = deque.removeLast();
                    result[popElem[1]] = i - popElem[1];
                }
            }
            deque.addLast(new Integer[]{temperatures[i], i});
        }
        return result;
    }
}
相关推荐
惯导马工1 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农2 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了3 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo3 小时前
322:零钱兑换(三种方法)
算法
NAGNIP21 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队1 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法