LeetCode

[LeetCode] Medium - 739 Daily Temperatures

NIMHO 2022. 12. 18. 09:32
728x90

▶739 - Evaluate Reverse Polish Notation

문제

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

 

예제

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Input: temperatures = [30,60,90]
Output: [1,1,0]

 

풀이

stack을 하나 만들어서, 온도를 가져올 때마다 전의 값을 비교해준다.온도가 더 높아지면 pop 해주고 while을 통해 반복한다.

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        stack = []
        answer = [0 for _ in range(len(temperatures))]

        for i, temp in enumerate(temperatures):
            while stack and temp > temperatures[stack[-1]]:
                last = stack.pop()
                answer[last] = i - last
            stack.append(i)
        
        return answer

시간적으로 봤을 땐 그렇게 효율적이지 않은 코드인 것 같다.

728x90