iT邦幫忙

2025 iThome 鐵人賽

0
生成式 AI

Chatting with ChatGPT——一天學習一題Leetcode系列 第 27

加油! 739. Daily Temperatures (Medium)

  • 分享至 

  • xImage
  •  

今天的題目大意是:給定一個陣列 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;
    }
}

上一篇
雖然斷賽但還是要打完.......
下一篇
快結束了~
系列文
Chatting with ChatGPT——一天學習一題Leetcode30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言