문제 링크 : https://leetcode.com/problems/daily-temperatures/
일일 온도 T 목록이 주어지면 입력의 각 날짜에 대해 더 따뜻한 온도까지 기다려야하는 일 수를 알려주는 목록을 반환합니다. 이것이 가능한 미래 날이 없으면 대신 0을 입력하십시오.
물론 일일이 탐색하는 Bruteforce 방식도 있지만
좀더 효율적인 방식으로 stack을 이용하는 방식이 있다.
일단 temperature 를 stack에 기억해둔다
그리고 이후에 더 큰 temperature값이 있으면 스택에서 pop해주고 인덱스값을 빼준다.
class Solution:
def dailyTemperatures(self, t: List[int]) -> List[int]:
ans = [0] * len(t)
s = []
for i,tem in enumerate(t):
while s and t[s[-1]]< tem:
idx = s.pop()
ans[idx] = i - idx
s.append(i)
return ans