| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 | 31 |
- LeetCode
- binary search
- leetcode 풀기
- 파이썬 릿코드
- 잇츠디모
- 알고리즘풀기
- 파이썬릿코드
- 릿코드풀이
- 알고리즘풀이
- 릿코드풀기
- python sorted
- leetcode풀이
- python Leetcode
- 릿코드 풀기
- python 알고리즘
- python 릿코드
- 코틀린기초
- python xor
- 파이썬알고리즘
- 상가수익률계산기
- python priority queue
- 파이썬 프로그래머스
- 릿코드 파이썬
- 파이썬 알고리즘 풀기
- 릿코드
- 파이썬릿코드풀기
- 파이썬알고리즘풀기
- leetcode풀기
- python zip_longest
- 파이썬 알고리즘
- Today
- Total
소프트웨어에 대한 모든 것
LeetCode 풀기 - 739. Daily Temperatures 본문
739. Daily Temperatures
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
문제)

솔루션1)
Brute-force로 접근해서 문제를 풀었더니 "Time Limit Exceeded"가 발생합니다.
시간 복잡도 : O(M^2)
공간 복잡도 : O(1)
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
t = temperatures
max_t = max(t)
ret = []
for i, t1 in enumerate(t):
if t1 >= max_t:
ret.append(0)
continue
for j in range(i+1, len(t)):
if t1 < t[j]:
ret.append(j-i)
break
else:
ret.append(0)
return ret
솔루션2)
monotonic stack(단조 스택)을 사용해서 시간 복잡도를 O(n)로 줄입니다.
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
ans = [0] * len(temperatures)
q = deque()
for idx, tmp in enumerate(temperatures):
while q and temperatures[q[-1]] < tmp:
ans[q[-1]] = idx - q[-1]
q.pop()
q.append(idx)
return ans
참고:
https://labuladong.gitbook.io/algo-en/ii.-data-structure/monotonicstack
Special Data Structure: Monotonic Stack - algo-en
Give you T = [73, 74, 75, 71, 69, 72, 76, 73], and you return [1, 1, 4, 2, 1, 1, 0, 0]. Explanation The first day is 73 degrees Fahrenheit, and the next day is 74 degrees Fahrenheit, which is higher than 73 degrees Fahrenheit.So for the first day, you can
labuladong.gitbook.io
'알고리즘 > LeetCode' 카테고리의 다른 글
| LeetCode 풀기 - 19. Remove Nth Node From End of List (0) | 2021.11.15 |
|---|---|
| LeetCode 풀기 - 876. Middle of the Linked List (0) | 2021.11.15 |
| LeetCode 풀기 - 1413. Minimum Value to Get Positive Step by Step Sum (0) | 2021.11.12 |
| LeetCode 풀기 - 167. Two Sum II - Input Array Is Sorted (0) | 2021.11.12 |
| LeetCode 풀기 - 283. Move Zeroes (0) | 2021.11.12 |