LeetCode739 每日温度(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 iᵗʰ 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 <= 10⁵
30 <= temperatures[i] <= 100
方法
单调栈法
遍历数组的数字,将没找到等待时间的数字存入栈中(没找到等待时间意味着截止到遍历的当前数,还没有比它大的数),若遇到比栈中元素大的值(从栈顶开始比较)则记录等待时间并从栈中取出,在栈中未找到等待时间的数字默认等待时间为0
- 时间复杂度:O(n),n为数组的长度
- 空间复杂度:O(n),最坏情况下所有数字都要进栈
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int length = temperatures.length;
Deque<Integer> stack = new LinkedList<>();
int[] result = new int[length];
for(int i=0;i<length;i++){
int temperature = temperatures[i];
while(!stack.isEmpty()&&temperature>temperatures[stack.peek()]){
int preIndex = stack.pop();
result[preIndex] = i - preIndex;
}
stack.push(i);
}
return result;
}
}

浙公网安备 33010602011771号