LeetCode739每日温度

题目描述

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

解析

  每次往栈中添加下标,如果遇到比栈顶元素对应的温度高,说明找到了栈顶的温度,出栈并入栈当前温度。

public int[] dailyTemperatures(int[] temperatures) {
        int[] res = new int[temperatures.length];
        Deque<Integer> s = new LinkedList<>();
        s.push(0);
        for(int i = 1; i < temperatures.length; i++) {
            while (!s.isEmpty() && temperatures[s.peek()] < temperatures[i]) {
                int pre = s.pop();
                res[pre] = i - pre;
            }
            s.push(i);
        }
        return res;
    }

在这里插入图片描述
  时间消耗最少的方式是动态规划,从后往前遍历:

  • 如果第 i+1 天的温度大于第 i 天的温度,那么 dp[i] = 1。
  • 如果第 i+1 天的温度不大于第 i 天的温度,那么查看 dp[i+1]:
    • 如果 dp[i+1] 是非零的,说明从第 i+1 天开始,有一个已知的更热的天在 i+1 + dp[i+1]。接下来检查那一天的温度是否高于第 i 天:
      • 如果是,dp[i] 就是 1 + dp[i+1]。
      • 如果不是,继续向后查看,直到找到更热的一天或者查看到数组的尽头。
public int[] dailyTemperatures(int[] temperatures) {
        int n=temperatures.length;
        int[] dp=new int[n];
        for(int i=n-2;i>=0;i--){
            int j=i+1;
            while(j<n && temperatures[j]<=temperatures[i] && dp[j]!=0){
                j+=dp[j];
            }
            if(j<n &&temperatures[j]>temperatures[i]){
                dp[i]=j-i;
            }
        }
        return dp;
    }

在这里插入图片描述
  虽然从此题提交的结果来看,动态规划耗时更短,但是使用栈,最好最坏的复杂度都是O(n),而使用动态规划最好为O(n),最坏是O(n^2),因此实际开发还是建议使用栈的方式来解决问题。

相关推荐

  1. LeetCode739每日温度

    2024-06-18 23:54:05       36 阅读
  2. Leetcode 739. 每日温度

    2024-06-18 23:54:05       30 阅读
  3. 739. 每日温度

    2024-06-18 23:54:05       18 阅读
  4. LeetCode-739. 每日温度【栈 数组 单调栈】

    2024-06-18 23:54:05       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-18 23:54:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-18 23:54:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-18 23:54:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-18 23:54:05       18 阅读

热门阅读

  1. 从零学习es8

    2024-06-18 23:54:05       6 阅读
  2. Stage模型

    2024-06-18 23:54:05       6 阅读
  3. 正规式理解

    2024-06-18 23:54:05       5 阅读
  4. 一文看懂E2PROM、FLASH等芯片,软件开发

    2024-06-18 23:54:05       6 阅读
  5. Vue3源码【三】—— createApp执行流程源码分析

    2024-06-18 23:54:05       4 阅读
  6. 华为安全Security认证,你了解多少?

    2024-06-18 23:54:05       7 阅读
  7. MySQL常用函数

    2024-06-18 23:54:05       5 阅读