当前位置: 首页 > article >正文

【Hot100】LeetCode—739. 每日温度

目录

  • 1- 思路
    • 单调栈
  • 2- 实现
    • 739. 每日温度——题解思路
  • 3- ACM 实现


  • 原题链接:739. 每日温度

1- 思路

单调栈

  • 寻找当前位置的下一个比他大的元素的位置
  • 利用 Stack 栈维护一个单调栈
    • 当前元素 <= 栈顶元素,直接压栈
    • 否则
      • 利用 while 循环判断

2- 实现

739. 每日温度——题解思路

在这里插入图片描述

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int len = temperatures.length;
        int[] res = new int[len];
        if(len == 0 || temperatures==null){
            return res;
        }

        Stack<Integer> st = new Stack<>();
        
        // 单调 递增,比 poll 顶小的直接压栈
        // 否则弹出更新结果,栈存储的是下标
        st.push(0);
        for(int i = 1 ; i < len ; i++){
            int nowNum = temperatures[i];
            if(nowNum<= temperatures[st.peek()]){
                st.push(i);
            }else{
                while(!st.isEmpty() && nowNum > temperatures[st.peek()]){
                    res[st.peek()] = i-st.peek();
                    st.pop();
                }
                st.push(i);
            }
        }

        return res;
    }
}

3- ACM 实现

public class temperature {


    public static int[] dailyT(int[] temperature){
        // 计算每日温度
        int len = temperature.length;
        int[] res = new int[len];
        if(len==0 || temperature== null){
            return res;
        }
        // 单调栈
        Stack<Integer> st = new Stack<>();
        st.push(0);
        for(int i = 1 ; i < len;i++){
            int nowNum = temperature[i];
            if(nowNum<= temperature[st.peek()]){
                st.push(i);
            }else{
                while (!st.isEmpty() && nowNum>temperature[st.peek()]){
                    res[st.peek()] = i - st.peek();
                    st.pop();
                }
                st.push(i);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String[] parts = input.split(" ");
        int[] nums = new int[parts.length];
        for(int i = 0 ; i < parts.length;i++){
            nums[i] = Integer.parseInt(parts[i]);
        }
        int[] res = dailyT(nums);
        for(int i:res){
            System.out.print(i+" ");
        }
    }
}


http://www.kler.cn/a/300011.html

相关文章:

  • 【Hot100】LeetCode—322. 零钱兑换
  • 关于武汉芯景科技有限公司的IIC缓冲器芯片XJ4307开发指南(兼容LTC4307)
  • 网络安全(sql注入)
  • DS18B20的C语言驱动
  • 基础算法(2)——滑动窗口
  • 针对中小企业数智化需求,新华三重磅发布 SMB 系列新品
  • 某仿soul欲音社交系统存在任意文件读取漏洞
  • 重修设计模式-结构型-代理模式
  • 音视频入门基础:WAV专题(9)——FFmpeg源码中计算WAV音频文件每个packet的duration和duration_time的实现
  • flinkcdc 问题记录篇章
  • 只有IP地址没有域名怎么实现HTTPS访问?
  • 【高级编程】Java IO流(补)序列化 反序列化
  • Pyspark下操作dataframe方法(1)
  • eNUM 原理概述(VoNR VoLTE适用) eNUM 报文解析
  • Vue2使用Vue CLI学习笔记
  • python 实现kadanes卡达内斯算法
  • 基于协同过滤算法+SpringBoot+Vue+MySQL的商品推荐系统
  • 人工智能帮你管理 ADHD 的7种方法
  • [Git使用] 实战技巧
  • 建造者模式builder