leetcode_739每日溫度

題目

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

中文翻譯:已知每日溫度列表T,求每個元素(當前溫度值)和下一個比當前溫度還高的元素 之間的索引(天數)差距,溫度不會再高了則賦值爲0

解法1

class Solution:
    def dailyTemperatures(self, T):
        """
        實現思路:
        1.維護一個單調遞減的棧即可,
            每次遇到新的元素大於棧頂記錄的元素值,將棧頂元素彈棧,並將相應的溫差值放入結果列表,
            然後循環比較棧頂元素和新元素,直到棧頂元素大於新元素位置,最後把新元素壓棧
        2.注意:棧中記錄元素的位置信息,這樣可以獲取元素值,也可以直接進行每日溫差的計算;
        :param T:
        :return:
        """
        ans = [0] * len(T)  # 列表元素賦初值爲零
        queue = []  # queue爲入棧元素的位置信息`在這裏插入代碼片`
        for i, val in enumerate(T):
            # len(queue)爲1時不考慮,確保棧中有可以比較的對象;
            # queue[-1]爲棧頂元素的位置
            # T[queue[-1]] 通過queue棧頂元素位置查看T中對應的元素
            while len(queue) > 0 and val > T[queue[-1]]:
                pre_i = queue.pop()
                ans[pre_i] = i - pre_i
            queue.append(i)  # 將元素的下標壓入棧中
        return ans


RES = Solution().dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73])
print(RES)

解法2

"""
根據題意,從最後一天推到第一天,這樣會簡單很多。因爲最後一天顯然不會再有升高的可能,結果直接爲0。
再看倒數第二天的溫度,如果比倒數第一天低,那麼答案顯然爲1,如果比倒數第一天高,又因爲倒數第一天
對應的結果爲0,即表示之後不會再升高,所以倒數第二天的結果也應該爲0。
自此我們容易觀察出規律,要求出第i天對應的結果,只需要知道第i+1天對應的結果就

可以:

- 若T[i] < T[i+1],那麼res[i]=1;

- 若T[i] > T[i+1]
  - res[i+1]=0,那麼res[i]=0;

  - res[i+1]!=0,那就比較T[i]和T[i+1+res[i+1]](即將第i天的溫度與比第i+1天大的那天的溫度進行比較)

"""

def daily_temperatures(self, T):
    """
    :type T: List[int]
    :rtype: List[int]
    """
    res = [0] * len(T)

    def get_res(i, j):
        if T[i] < T[j]:
            return j - i
        else:
            if res[j] == 0:
                return 0
            else:
                return get_res(i, j + res[j])

    for i in range(len(T) - 2, -1, -1):
        res[i] = get_res(i, i + 1)

    return res

解法2_小結

  • k-1 元素 和k 元素進行比較,如果k 元素大於k-1 元素, 一切好商量,只需要將兩者下標相減,思考下此處爲何不直接返回1
  • 在不滿足第一個條件後,當k元素的res爲0,代表接下來都不會有更高的溫度,相應位置直接賦值爲0
  • 在不滿足第二個條件後,將第k-1 元素和k+res[k] 元素進行遞歸調用,直到找到比k-1 元素大的元素,將兩者下標直接相減即可

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/daily-temperatures
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

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