[LeetCode] 739. Daily Temperatures

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

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

Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]

Example 3:
Input: temperatures = [30,60,90]
Output: [1,1,0]

Constraints:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100

每日温度。

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/daily-temperatures
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

思路依然是单调栈,而且这个题应该是一个单调递减栈。

具体做法是创建一个 stack,遍历数组,依然是把数组的下标放进 stack;若当前 stack 不为空且栈顶元素背后指向的温度 (temperatures[stack.peek()]) 小于当前温度 (temperatures[i]),则弹出栈顶 index,在结果集里面的对应 index 可以记录 i - index,这就是 index 和他自己之后一个高温天气的时间差。

复杂度

时间O(n)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] res = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
int cur = temperatures[i];
while (!stack.isEmpty() && cur > temperatures[stack.peekLast()]) {
int j = stack.pollLast();
res[j] = i - j;
}
stack.offerLast(i);
}
return res;
}
}

JavaScript实现

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

[LeetCode] 739. Daily Temperatures
https://shurui91.github.io/posts/3636396652.html
Author
Aaron Liu
Posted on
March 15, 2020
Licensed under