单调栈系列~LeetCode739.每日温度(中等)
实现思路:
- 利用单调栈的思路求出元素的下一个更大元素。
- Stack用来存储数组下标。
- 当前元素的值大于栈顶元素 && 栈不为空 -> 将栈顶元素(index)弹出,栈顶的值对应的元素的下一个更大的元素是 当前元素。
- 不满足前一个条件的时候将当前元素的下标入栈。
class Solution {
public int[] dailyTemperatures(int[] T) {
Stack<Integer> stack = new Stack<>();
int []res = new int[T.length];
Arrays.fill(res, 0);
for(int i=0; i<T.length; i++){
while(!stack.isEmpty() && T[stack.peek()] < T[i]){
int index = stack.pop();
res[index] = i - index;
}
stack.push(i);
}
return res;
}
}