iT邦幫忙

2023 iThome 鐵人賽

DAY 24
0

Googler幫查了一波
HR還活著~~!
那我只是單純被忽略了(X

先繼續刷題吧 /images/emoticon/emoticon02.gif

Daily Temperatures

Q: https://leetcode.com/problems/daily-temperatures/

/**
    dp[n]: after n days warming

    temperatures[n] > temperatures[n-1]
    dp[n-1] = 1

    temperatures[n] < temperatures[n-1]
    dp[n-1] = 1 + dp[n-1]   ->    (new)n = n-1 ----> loop
 */
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] answer = new int[n];
        for (int i = n - 1;i >= 0;i--) {
            if (i == n - 1) {
                answer[i] = 0;
            } else {
                if (temperatures[i] < temperatures[i+1]) {
                    answer[i] = 1;
                } else {
                    int tempDay = 1 + answer[i + 1];
                    int tempIndex = i + 1 + answer[i+1];
                    while(tempIndex < n) {
                        if (temperatures[tempIndex] > temperatures[i]) {
                            answer[i] = tempDay;
                            break;
                        } else if (answer[tempIndex] == 0) {
                            answer[i] = 0;
                            break;
                        } else {
                            tempDay += answer[tempIndex];
                            tempIndex = tempIndex + answer[tempIndex];
                        }
                    }
                }
            }
        }
        return answer;
    }
}

上一篇
09/23
下一篇
09/25
系列文
30天準備google面試30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言