welcome to my blog
LeetCode Top 100 Liked Questions 739. Daily Temperatures (Java版; Medium)
题目描述
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]
class Solution {
public int[] dailyTemperatures(int[] T) {
int n = T.length;
if(n==0){
return new int[]{};
}
int[] res = new int[n];
Stack<Integer> s = new Stack<>();
for(int i=0; i<n; i++){
while(!s.isEmpty() && T[i]>T[s.peek()]){
int j = s.pop();
res[j] = i - j;
}
s.push(i);
}
//
return res;
}
}
第一次做; 单调栈, 遍历阶段+清算阶段
/*
找某个数右边离它最近的比它大的数
很有单调栈的感觉, 不过单调栈更复杂, 可以找到两侧比自己大并且距离自己最近的数
用单调栈的流程解决
单调栈:遍历阶段; 清算阶段
*/
import java.util.Stack;
class Solution {
public int[] dailyTemperatures(int[] T) {
//input check
if(T==null || T.length==0)
return new int[]{};
//
int[] res = new int[T.length];
//单调栈, 栈中存索引(信息量大!); 栈底到栈顶是递减的
Stack<Integer> stack = new Stack<>();
//遍历阶段
for(int i=0; i<T.length; i++){
if(stack.isEmpty() || T[i]<=T[stack.peek()])
//将索引入栈
stack.push(i);
else{
while(!stack.isEmpty() && T[i]>T[stack.peek()]){
int index = stack.pop();
res[index] = i - index;
}
stack.push(i);
}
}
//清算阶段;由于数组默认值是0, 和清算阶段的操作逻辑一样, 所以就不用执行操作了,直接返回结果
return res;
}
}