[739] LeetCode. Daily temperature

Problem Description

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].

Given a list of daily temperature T, returns a list like this, the input of each day, it tells you how many days to wait until the temperature rises. If there is no future any day this is possible and replace them with 0.
For example, a given temperature T = [73, 74, 75 , 71, 69, 72, 76, 73], the output should be [1,1,4,2,1,1,0,0].
Note: the length of the temperature will be in the range [1,30000]. Each temperatures are [30, 100] integer in the range.

 

Python implementation

Use stack: According to the description of the problem, but it finally returns to the subject of the difference is actually under the target value, so we need to store up to compare the observed value is the index of each value. In addition it can be imaginary, a value of more than an hour before, we need to continue to discuss a value stored after when; when a value is greater than the previous one, the previous one we will not discuss, is also a value after the save up to continue the discussion that follows. Therefore, this process can be implemented by the stack, the index into the stack, the calculation result for the difference between desired.

class Solution(object):
    def dailyTemperatures(self, T):
        """
        :type T: List[int]
        :rtype: List[int]
        """ 
        
        if T == None or len(T) == 0:
            return []
        
        # Stack: greater then pop; smaller then append.
        stack = []
        ret = [0] * len(T)
        
        for i in range(len(T)):
            while len(stack) > 0 and T[i] > T[stack[-1]]:
                ret[stack[-1]] = i - stack[-1]
                stack.pop(-1)
                
            # Save indeces in the stack.
            stack.append(i)
            
        return ret
        

 

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

 

Published 45 original articles · won praise 29 · views 20000 +

Guess you like

Origin blog.csdn.net/sinat_36645384/article/details/103971141