Always Be Wise

스택 : 일일 온도(리트코드 739번) 본문

알고리즘/리트코드

스택 : 일일 온도(리트코드 739번)

bewisesh91 2022. 2. 2. 21:35
728x90

▶ 문제 : https://leetcode.com/problems/daily-temperatures/

 

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

##### 문제 #####
# 매일의 화시 온도 리스트를 입력 받아서, 더 따뜻한 날씨를 위해서는 며칠을 기다려야 하는지 출력하라.

##### 입력 #####
# temperatures = [73, 74, 75, 71, 69, 72, 76, 73]

##### 출력 #####

# [1, 1, 4, 2, 1, 1, 0, 0]

 

▶ 접근 방법

입력 받은 온도 리스트에서 인덱스와 현재 온도를 반복문을 통해 구하고,
스택에 값이 있고, 스택의 마지막 값을 인덱스로 하는 온도 리스트의 값이 현재 온도보다 낮다면,
스택에서 값을 꺼내 해당 값을 answer 리스트의 인덱스로 하는 값을 갱신해준다.
만약 해당하지 않는다면 스택에 입력 받은 온도 리스트의 현재 인덱스를 추가해준다.

 

▶ 풀이 코드

def daily_temperatures(temperatures:list) -> list:
    answer = [0] * len(temperatures)
    stack = []
    for i, cur in enumerate(temperatures):
        while stack and cur > temperatures[stack[-1]]:
            last = stack.pop()
            answer[last] = i - last
        stack.append(i)
    
    return answer

temperatures = [73, 74, 75, 71, 69, 72, 76, 73]

print(daily_temperatures(temperatures))

 

▶ 관련 링크

2022.02.02 - [알고리즘/리트코드] - 스택 : 유효한 괄호(리트코드 20번)

2022.02.02 - [알고리즘/리트코드] - 스택 : 중복 문자 제거(리트코드 316번)

Comments