数据结构与算法-练习打卡day5(每日温度)

数据结构与算法-练习打卡day5

问题:

题目地址,点我
在这里插入图片描述

解题:

分析:至少需要两层,最简单就是两层for循环,也可以引入单调栈,可以去掉一些不是单调的中间值,节省遍历个数

class Solution {
    /**
	 * 	public int[] dailyTemperatures(int[] temperatureArray) {
	 * 		int[] diffArray = new int[temperatureArray.length];
	 * 		int x = temperatureArray.length - 1;
	 * 		for (int i = 0; i < temperatureArray.length; i++) {
	 * 			int temperature = temperatureArray[i];
	 * 			for (int j = 1; j < temperatureArray.length - i; j++) {
	 * 				int next = temperatureArray[i + j];
	 * 				if (next > temperature) {
	 * 					diffArray[i] = j;
	 * 					break;
	 *                                }* 			}
	 * 		}
	 * 		diffArray[x] = 0;
	 * 		return diffArray;
	 * 	}
	 */
	public int[] dailyTemperatures(int[] temperatureArray) {
		LinkedList<int[]> stack = new LinkedList<>();
		stack.addFirst(new int[]{temperatureArray[0], 0});
		for (int i = 1; i < temperatureArray.length; i++) {
			while (stack.size() > 0 && stack.getFirst()[0] < temperatureArray[i]) {
				int index = stack.getFirst()[1];
				temperatureArray[index] = i - index;
				stack.removeFirst();
			}
			stack.addFirst(new int[]{temperatureArray[i], i});
		}
		for (int[] ints : stack) {
			temperatureArray[ints[1]] = 0;
		}
		return temperatureArray;
	}
}

性能:

单调栈确实节省了很多时间
在这里插入图片描述


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值