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
풀이 과정
각 날짜의 온도가 주어질 때, 어떤 날짜에서 며칠을 기다려야 더 따뜻한 날이 되는지 출력하는 문제이다.
2중 for문 돌려서 O(N^2)로도 해결할 수 있겠지만, 스택을 활용해서 더 효율적으로 문제를 해결할 수 있다.
수의 index를 스택에 저장하면서, 스택탑의 index 날짜의 온도보다 더 따뜻한 날의 index가 들어오면 스택을 pop하면서 따뜻한 날의 index - 스택 탑의 index를 계산해서 정답 리스트에 저장해주면 문제를 해결할 수 있다.
소스 코드
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
answer = [0 for _ in range(len(temperatures))]
for a, b in enumerate(temperatures):
while stack and temperatures[stack[-1]] < b:
last = stack.pop()
answer[last] = a - last
stack.append(a)
return answer
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 232. Implement Queue using Stacks [Python] (0) | 2022.08.02 |
---|---|
LeetCode - 225. Implement Stack using Queues [Python] (0) | 2022.08.02 |
LeetCode - 316. Remove Duplicate Letters [Python] (0) | 2022.08.02 |
LeetCode - 20. Valid Parentheses [Python] (0) | 2022.07.28 |
LeetCode - 328. Odd Even Linked List [Python] (0) | 2022.07.28 |