Programming

Leetcode-739. Daily Temperatures

Leetcode-739. Daily Temperatures

<解題>


class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Deque<Integer> stack = new ArrayDeque<>();
        
        // 創建一個整數陣列用來存儲每一天需要等待的天數
        int[] res = new int[temperatures.length];

        // 遍歷溫度陣列
        for (int i = 0; i < temperatures.length; i++) {
            // 使用 while 迴圈處理堆疊中的元素,直到堆疊為空或當前溫度不再大於堆疊頂部元素對應的溫度
            while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
                // 從堆疊中彈出頂部元素的索引,記為 idx
                int idx = stack.pop();
                // 計算當前索引 i 減去 idx,這代表需要等待的天數,將結果存儲在 res 陣列的 idx 位置
                res[idx] = i - idx;
            }
            // 將當前索引 i 壓入堆疊,以便之後比較
            stack.push(i);
        }
        // 返回存儲了每一天需要等待的天數的 res 陣列
        return res;
    }
}