今天的題目大意是:給定一個陣列 temperatures,代表每天的溫度。回傳一個陣列 answer,其中 answer[i] 表示第 i 天之後,要等幾天才會有更高的溫度。如果之後沒有更高溫度,則為 0。
核心思路
對每一天,向後搜尋找到第一個更高溫度的日子!
import java.util.Stack;
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] answer = new int[n];
Stack<Integer> stack = new Stack<>(); // 存放索引
for (int i = 0; i < n; i++) {
// 當前溫度比 stack 頂部的溫度高
// 代表 stack 頂部那天找到答案了
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int prevIndex = stack.pop();
answer[prevIndex] = i - prevIndex;
}
// 當前索引入 stack,等待未來找到答案
stack.push(i);
}
// stack 中剩下的索引,之後沒有更高溫度,保持為 0
return answer;
}
}