[LeetCode] 739. Daily Temperatures

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

每日温度。题意是给一个数组,表示每天的气温,请返回一个数组,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。例子,

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

思路依然是单调栈,而且这个题应该是一个单调递增栈。单调栈的题目都会以这个tag展示。创建一个stack,遍历数组,依然是把数组的下标放进stack;若当前stack不为空且栈顶元素背后指向的温度小于试图放进去的index背后的温度,则弹出栈顶index,在结果集里面的对应index可以记录i - index,这就是index和他自己之后一个高温天气的时间差。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int[] dailyTemperatures(int[] T) {
 3         Stack<Integer> stack = new Stack<>();
 4         int[] res = new int[T.length];
 5         for (int i = 0; i < T.length; i++) {
 6             while (!stack.isEmpty() && T[i] > T[stack.peek()]) {
 7                 int index = stack.pop();
 8                 res[index] = i - index;
 9             }
10             stack.push(i);
11         }
12         return res;
13     }
14 }

JavaScript实现

 1 /**
 2  * @param {number[]} T
 3  * @return {number[]}
 4  */
 5 var dailyTemperatures = function (T) {
 6     let stack = [];
 7     let res = new Array(T.length).fill(0);
 8     for (let i = 0; i < T.length; i++) {
 9         while (stack.length && T[i] > T[stack[stack.length - 1]]) {
10             let index = stack.pop();
11             res[index] = i - index;
12         }
13         stack.push(i);
14     }
15     return res;
16 };

单调栈相关题目

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12495828.html