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

每日温度(力扣)单调栈 JAVA

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

示例 1:

输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]

示例 2:

输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]

示例 3:

输入: temperatures = [30,60,90]
输出: [1,1,0]

提示:

1 <= temperatures.length <= 10^5
30 <= temperatures[i] <= 100

解题思路:

1、本题需要栈来展缓储存数据,在遍历新数据时判断其是否比前面的数据大,方便进行后续操作

和 下一个更大元素 非常类似。

2、不同点是本题元素有重复!所以无法用map!

朴素代码:

class Solution {public int[] dailyTemperatures(int[] temperatures) {Deque<Integer> stacktmpts = new ArrayDeque<Integer>();Deque<Integer> stackindex = new ArrayDeque<Integer>();int len = temperatures.length;int res[] = new int[len];for(int i = 0; i < len; i ++) {while(!stacktmpts.isEmpty() && temperatures[i] > stacktmpts.peekLast()) {res[stackindex.peekLast()] = i - stackindex.pollLast();stacktmpts.pollLast();}stacktmpts.add(temperatures[i]);stackindex.add(i);}while(!stackindex.isEmpty()) res[stackindex.pollLast()] = 0;return res;}
}

在这里插入图片描述
比较笨用两个栈分别存储下标和值

值得注意的是数组中下标和值是一对一的关系,所以理论上只存储下标即可

优化代码:

class Solution {public int[] dailyTemperatures(int[] temperatures) {Deque<Integer> stack = new ArrayDeque<Integer>();int len = temperatures.length;int res[] = new int[len];for(int i = 0; i < len; i ++) {while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peekLast()]) {res[stack.peekLast()] = i - stack.pollLast();}stack.add(i);}while(!stack.isEmpty()) res[stack.pollLast()] = 0;return res;}
}

在这里插入图片描述

代码:

class Solution {public int[] dailyTemperatures(int[] temperatures) {int length = temperatures.length;int[] ans = new int[length];Deque<Integer> stack = new LinkedList<Integer>();for (int i = 0; i < length; i++) {while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {int prevIndex = stack.pop();ans[prevIndex] = i - prevIndex;}stack.push(i);}return ans;}
} 

在这里插入图片描述

http://www.lryc.cn/news/123571.html

相关文章:

  • 博客项目(Spring Boot)
  • 修改Jenkins存储目录
  • 数据结构【第4章】——栈与队列
  • android webview 显示灰度网页
  • Linux操作系统的基础使用技能的训练大纲(超级详细版本适合于初学者)
  • 【变形金刚02】注意机制以及BERT 和 GPT
  • 一个脚本 专治杂乱
  • springboot 基础
  • web集群学习:基于nginx的反向代理和负载均衡
  • 编程小窍门: 一个简单的go mutex的小例子
  • 【工作记录】mysql中实现分组统计的三种方式
  • 马来西亚的区块链和NFT市场调研
  • [保研/考研机试] KY109 Zero-complexity Transposition 上海交通大学复试上机题 C++实现
  • Linux零基础快速入门到精通
  • ARM02汇编指令
  • 从初学者到专家:Java方法的完整指南
  • 【生成式AI】ProlificDreamer论文阅读
  • C++元编程——模拟javascript异步执行
  • 【JavaEE】懒人的福音-MyBatis框架—复杂的操作-动态SQL
  • Springboot 默认路径说明
  • springboot注册拦截器与返回统一标准响应格式
  • 卷王特斯拉又全网降价了,卷死车企们
  • wiley:revision 流程
  • 【论文阅读】基于深度学习的时序预测——Pyraformer
  • 玩转IndexedDB,比localStorage、cookie还要强大的网页端本地缓存
  • RedisDesktopManager连不上redis问题解决(小白版)
  • 蓝帽杯 取证2022
  • MyBatis and or使用列表控制or条件
  • C语言刷题训练【第11天】
  • 正则表达式的使用