href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
这是leetcode的第729题--Daily Temperatures
题目 Given a list of daily temperatures, produce a list 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 temperatures = [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]. 思路 看了别人的答案,以及评论(如下),自己再写的,
When I saw the question in this competition, I firstly think about Monotonous stack inspired by Largest Rectangle in Histogram. Because Monotonous stack can help us find first largest element in O(n) time complexity. But I can't implement use Monotonous stack idea to solve the problem.But you did it, brilliant bro.
总结 多读书
class Solution: def dailyTemperatures(self, temperatures): """ :type temperatures: List[int] :rtype: List[int] """ n = len(temperatures) stk =[] rst=[0]*n for i in range(n): while stk and temperatures[stk[-1]]<temperatures[i]: tmp = stk.pop() rst[tmp]=i-tmp stk.append(i) return rst
2017-12-1
![divider][divider] * ## Merge k Sorted Lists --leetcode23 题目 Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 思路 多路归并,用堆更快,而且python中提供了此模块heapq,注意其用法,这不是一个类,而是一些函数,还有就是merge函数接收的是一些lists,所以要将data解包,见代码21行
show me the code
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None import heapq class Solution: def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ li=[i for i in lists if i !=None] if not li:return [] data=[] for i in li: data.append([]) while i!=None: data[-1].append(i.val) i=i.next hp =list(heapq.merge(*data)) rst = ListNode(heapq.heappop(hp)) last = rst while hp: last.next=ListNode(heapq.heappop(hp)) last = last.next last.next = None return rst