본문 바로가기
카테고리 없음

[리트코드/파이썬] 739. Daily Temperatures (스택)

by summer_light 2023. 12. 13.

[리트코드/파이썬] 739. Daily Temperatures (스택) 

난이도: Medium

739. Daily Temperatures

 

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.

Example 1:

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]

Example 2:

Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]

Example 3:

Input: temperatures = [30,60,90]
Output: [1,1,0]

Constraints:

  • 1 <= temperatures.length <= 105
  • 30 <= temperatures[i] <= 100

[내 풀이]

※ 소요시간 : 13

※ 풀이 전략

- 값이 증가할 때만 스택에서 빼기 때문에, stk에 남아있는 값들은 자연스레 내림차순이 된다. 

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        res = [0] * len(temperatures)
        stk = [] # 내림차순으로 들어갈 것
        for i, t in enumerate(temperatures):
            while stk and stk[-1][1] < t:
                si, st = stk.pop()
                res[si] = i-si
            stk.append((i,t))
        return res

 

※ 중요 포인트

- N=10^4 이므로 N^2 이상의 알고리즘은 쓰지 못한다. 따라서 리스트를 상수 번 루프 돌면서 해결해야 한다. 


 

 

 

댓글