题目描述

Leetcode 739 本题考察了栈的使用。题目输入是一段温度值列表,然后返回一个列表。这个列表包含了输入列表中每一天还有多少天温度升高。如果未来没有升高的情况,则输入 0。

# Example1:
# Input: T = [73, 74, 75, 71, 69, 72, 76, 73]
# Output: [1, 1, 4, 2, 1, 1, 0, 0] # 比如 index=0 这天温度为 73 度,index=1,这天为 74 度。
# 所以针对 index=0 这天,还需要 1 天温度会升高。 # 对于 index=2 这天,还需要 4 天才可以温度升高。

题目分析

通常的做法是从某一位置开始依次和该位置之后的温度进行比较,但这样就会出现冗余的情况。

拿 index=2 的温度来说,会和 71,69,72,76 依次做比较。但实际上经过此次比较,71,69 已

经找到比它本身温度高的答案了,复杂度为 O(N^2)

可以使用栈进行保存,栈里面保存的是当前栈顶元素的下标。而当前遍历元素的下标减去栈顶元素的

下标就是所需要经历的天数。每个元素最多被弹出和压入栈一次,因此为 O(N).

# Question: Daily Temperatures
# 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. # Example1:
# T = [73, 74, 75, 71, 69, 72, 76, 73]
# [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] class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
stack = []
stack_sky = [0] * len(T)
for index, element in enumerate(T):
if stack.__len__() > 0:
tem = T[stack[-1]]
while stack and element > tem:
stack_sky[stack[-1]] = index - stack[-1]
stack.pop()
if stack.__len__() > 0:
tem = T[stack[-1]]
stack.append(index) return stack_sky if __name__ == '__main__':
example_list_1 = [73, 74, 75, 71, 69, 72, 76, 73]
example_list_2 = [89, 62, 70, 58, 47, 47, 46, 76, 100, 70]
solution = Solution()
print(solution.dailyTemperatures(example_list_2))

最新文章

  1. metaWeblog Test
  2. 2016年12月27日 星期二 --出埃及记 Exodus 21:22
  3. PE355
  4. request模块提交数据
  5. python检测文件是否更新
  6. Body joints angle using Kinect
  7. Modbus通信协议详解
  8. Robot Framework学习笔记(九)------创建资源和用户关键字
  9. Masonry中的mas_makeConstraints方法
  10. 浏览器url地址殊字符转义编码
  11. MySQL删除foreign key_ERROR 1025 (HY000): Error on rename of './test_20180206/cc' to './test_20180206/#sql2-9ac-e' (errno: 152)
  12. 【sping揭秘】24、Spring框架对JMS的集成(无环境版,以后学MQ的时候再隆重介绍)& 任务调度和线程池
  13. Java_Properties
  14. rabbitMQ 3.6.15生产环境
  15. Select查询命令
  16. 学号 20175223 《Java程序设计》第2周学习总结
  17. R-FCN:安装训练自己的数据
  18. learning scala output to console
  19. JavaScript -- Window-状态栏
  20. 图像检索:一维直方图+欧几里得距离+flann+KNN

热门文章

  1. RSA公钥私钥原理及作用
  2. mongodb WiredTiger 内存分配
  3. spring boot 对某个接口进行次数限制,防刷。简易版。demo。
  4. 10月清北学堂培训 Day 7
  5. codeforces396A
  6. 模糊查询(附上源码和jquery-1.12.1.js,jquery-ui.js,jquery-ui.css)
  7. 使用C#代码调用Web API
  8. ISA真慢
  9. 阿里巴巴高可用技术专家襄玲:压测环境的设计和搭建 PTS - 襄玲 云栖社区 今天
  10. React拾遗(下)