Daily Temperatures - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def dailyTemperatures(t):
    ans = [0* len(t)
    stack = []
 
    for now_index, temperature in enumerate(t):
        while stack and temperature > t[stack[-1]]:
            pre_index = stack.pop()
            ans[pre_index] = now_index - pre_index
 
        stack.append(now_index)
    return ans
 
 
temperatures = [7374757169727673]  # Output: [1,1,4,2,1,1,0,0]
print(dailyTemperatures(temperatures))
cs

https://02082306.tistory.com/112 문제와 전체적인 구성이 비슷한 문제이다.
for 
    while
        pop
    append
구조를 가진다.

이 문제에서는 [0]으로 초기화 한 list인 ans를 만들어서 답을 저장했다. 
답이 순차적으로 저장될거라는 보장이 없기 때문이다.
temperatures에서 [75, 71, 69] 관계가 이 경우이다.

stack의 성질을 사용하여, stack[-1] 과 pop()을 통한 계산이 전부이다. stack[:-1]같은 작업보다는
while문을 사용하여 조건을 충족하면, stack에 쌓인 값들을 순차적으로 확인하며 pop() 해준다.

 

+ Recent posts