739. Daily Temperatures
Solution
幾個重點要想到
為了要知道每個元素左邊是否有溫度更高的存在,以及如果有間隔為多少天?
1. 從左至右去尋訪
要能知道間隔多少天-> 要能知道什麼時候有更高的溫度,需要資料結構去儲存
2. 由一個stack去紀錄之前的所有溫度,要放進去stack時,由於比目前的溫度小的植在stack中沒有意義,都刪除掉。因為後面的溫度可以直接找到目前的溫度是更高的溫度,所以不需要存放比目前溫度小的。
public int[] dailyTemperatures(int[] T) {
int n = T.length;
int[] result = new int[n];
Stack<Integer> s = new Stack<>();
for(int i = n-1; i >= 0; i--){
int cur = T[i];
while(!s.isEmpty() && T[s.peek()] <= cur) s.pop();
result[i] = s.isEmpty()? 0 : s.peek() - i;
s.push(i);
}
return result;
}
Last updated
Was this helpful?