Algorithm/Python

[LeetCode] 739. Daily Temperatures

🥭맹2 2021. 6. 6. 18:05

1. 문제

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. 접근 방법

stack입니다.

 

저번에 풀이했던 주식 가격과 매우 유사한 문제라 똑같이 접근하면 됩니다.

 

프로그래머스 주식 가격 풀이

https://maeng2world.tistory.com/168

 

3. 코드

python

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        stack = []
        answer = [0] * len(temperatures)
        for idx in range(len(temperatures)):
            while stack and temperatures[stack[-1]] < temperatures[idx]:
                pre_idx = stack.pop()
                answer[pre_idx] = idx-pre_idx
            stack.append(idx)
        return answer

4. 마치며

enumerate 사용 유무에 따라 많이 차이날까 싶었는데, 오히려 enumerate안쓰고 인덱스만으로 접근하는게 더 빠르고, 메모리도 덜 잡아먹네여

 

위가 enumerate쓴 거, 아래가 안쓴거

'Algorithm > Python' 카테고리의 다른 글

[LeetCode] 232. Implement Queue using Stacks  (0) 2021.06.06
[LeetCode] 225. Implement Stack using Queues  (0) 2021.06.06
[LeetCode] 20. Valid Parentheses  (0) 2021.06.06
[백준 2468] 안전영역  (0) 2021.06.06
[백준 7569] 토마토  (0) 2021.06.06