返回

LeetCode 739: 找出比当日报更高的气温

见解分享





**题目** 

给你一个长度为 n 的整数数组 `temperatures`,它表示按 **日期**  顺序每天录入的 **气温** 。

请你设计一个算法来找出每一天的天气将 **持续升高** (即严格升高)的天数。如果某一天将 **持续降低** ,即满足气温 **严格降低** ,则视为 **没有持续升高的天数****示例 1:** 

示例 1:

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

**示例 2:** 

示例 2:

  • 输入:temperatures = [34, 80, 81, 78, 72, 87]
  • 输出:[1, 1, 0, 1, 1, 0]

**示例 3:** 

示例 3:

  • 输入:temperatures = [75, 80, 78, 72]
  • 输出:[0, 0, 0, 0]

**提示:** 

1. `temperatures.length` 将在 [1, 10^4] 范围内
2. `temperatures[i]` 将在 [30, 100] 范围内

**限制:** 

不允许使用额外数组。你仅可以用常数时间复杂度来进行。

**方法一:** 
**单调栈** 

从后往前遍历 `temperatures`,用一个单调栈来存储未找到比它们更高的气温的温度。

1. 创建一个单调栈 `stack`
2. 倒叙遍历 `temperatures`
    1. 如果栈不为空,并且 `temperatures[i]` 比栈顶的温度大,则弹出栈顶的温度,并用 `temperatures[i]` 减去栈顶的温度,将差值压入栈中。
    2.`temperatures[i]` 压入栈中。
3.`stack` 为空时,说明所有温度都找不到比它们更高的温度,将 `0` 压入所有温度中。
4. `stack` 中存储的差值就是每个温度需要再等的天数。

**复杂度:** 

* 时间复杂度:O(n)
* 空间复杂度:O(n)

**示例 Java 代码:** 
public int[] nextGreaterElement(int[] tempertures) {
    Stack<Integer> stack = new Stacks<>();
    int[] res = new int[tempertures.length];
    
    for (int i = tempertures.length - 1; i >= 0; i++) {
        while (!stack.isEmpty() && tempertures[i] > tempertures[stack.pop()]) {
            res[i] = tempertures[i] - tempertures[stack.pop()];
        }
        stack.push(i);
    }
    
    while (!stack.isEmpty()) {
        res[stack.pop() = 0;
    }
    
    return res;
}