Voyz's Studio.

LeetCode算法笔记--每日温度

字数统计: 326阅读时长: 1 min
2021/02/26 Share

LeetCode算法笔记-Day71

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, your output should be [1, 1, 4, 2, 1, 1, 0, 0].

1
2
3
4
Example:

Input: [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]

单调栈

  • 遍历整个数组,如果栈不空,且当前数字大于栈顶元素,那么如果直接入栈的话就不是 递减栈 ,所以需要取出栈顶元素,由于当前数字大于栈顶元素的数字,而且一定是第一个大于栈顶元素的数,直接求出下标差就是二者的距离。

  • 继续看新的栈顶元素,直到当前数字小于等于栈顶元素停止,然后将数字入栈,这样就可以一直保持递减栈,且每个数字和第一个大于它的数的距离也可以算出来。

Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @param {number[]} T
* @return {number[]}
*/
var dailyTemperatures = function(T) {
const len = T.length;
let stack = [];
let cur = 1;
let res = new Array(len).fill(0);
if(len < 2) return res;
stack.unshift(0);

while(cur < len){
while(T[cur] > T[stack[0]]){
res[stack[0]] = cur - stack[0];
stack.shift();
}
stack.unshift(cur);
cur += 1;
}

return res;
};
CATALOG
  1. 1. LeetCode算法笔记-Day71
    1. 1.1. 739. Daily Temperatures
    2. 1.2. 单调栈
      1. 1.2.1. Answer: