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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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