题目
题目链接:https://leetcode-cn.com/problems/daily-temperatures/
题目解析:将温度数组的数组标志放入栈中,如果后面的温度有比它大的就弹出,并且与当前的温度比较然后放入结果数组中
代码
class Solution {
public int[] dailyTemperatures(int[] T) {
//创建结果数组
int[] result = new int[T.length];
//创建栈对象
Stack<Integer> stack = new Stack<>();
//遍历数组
for (int i = 0; i < T.length; i++) {
//如果栈为空就加入栈
if(stack.isEmpty()) {
stack.push(i);
}else {
//遍历栈
while(!stack.isEmpty()) {
//如果当前温度比栈中的温度要高
if(T[i]>T[stack.peek()]) {
//弹栈
int t = stack.pop();
//并将当前天数与比较的天数相减得到结果放入结果数组中
result[t]=i-t;
}else {
//如果没有就结束循环
break;
}
}
//将当前天数加入
stack.push(i);
}
}
return result;
}
}