739. 每日溫度 Leetcode Java

題目:

請根據每日 氣溫 列表,重新生成一個列表。對應位置的輸出爲:要想觀測到更高的氣溫,至少需要等待的天數。如果氣溫在這之後都不會升高,請在該位置用 0 來代替。

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

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

 

解題思路:

利用棧和數組

代碼實現:

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

            stack.push(i);
        }
        return res;

    }
}
//leetcode submit region end(Prohibit modification and deletion)

 

 複雜度:

時間O(n);

空間O(n);

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