739. 每日溫度

根據每日 氣溫 列表,請重新生成一個列表,對應位置的輸入是你需要再等待多久溫度纔會升高的天數。如果之後都不會升高,請輸入 0 來代替。

例如,給定一個列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的輸出應該是 [1, 1, 4, 2, 1, 1, 0, 0]

提示:氣溫 列表長度的範圍是 [1, 30000]。每個氣溫的值的都是 [30, 100] 範圍內的整數。


Review:

利用棧思想解題,把氣溫對應索引存入棧中,每遍歷一個溫度就與之前溫度比較,若大於之前溫度,則計算天數

此棧爲遞減棧


Code:

也可以使用數組實現棧,速度會快一些,但我就不浪費這個時間了

class Solution {
    public int[] dailyTemperatures(int[] T) {
        Stack<Integer> helper = new Stack<>();
        int[] res = new int[T.length];
        for (int i = 0; i < T.length; i++) {
            while (!helper.empty()&&T[helper.peek()]<T[i]){
                int temp = helper.pop();
                res[temp] = i-temp;
            }
            helper.push(i);
        }
        return res;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章