일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 생성형AI
- Greedy
- LeetCode
- Python3
- 슬라이딩윈도우
- two-pointer
- GenAI
- 릿코드
- slidingwindow
- SQL
- 리트코드
- 파이썬
- array
- stratascratch
- codeup
- sql코테
- Python
- gcp
- 니트코드
- heap
- nlp
- dfs
- 투포인터
- 코드업
- Stack
- 알고리즘
- 파이썬기초100제
- GenerativeAI
- 파이썬알고리즘
- 자연어처리
Archives
- Today
- Total
Tech for good
[Neetcode/Stack] Daily Temperatures 본문
https://neetcode.io/problems/daily-temperatures?list=neetcode150
NeetCode
neetcode.io
Approach 1 -> nest loop (time complexity: O(n^2))
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
res = []
# t = temperature[i]
for i, t in enumerate(temperatures):
j = i+1
while j < len(temperatures) and temperatures[i] >= temperatures[j]:
j+=1
if j == len(temperatures):
res.append(0)
else:
res.append(j-i)
Approach 2 -> stack (monotonically decreasing order)
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
res = [0] * len(temperatures)
stack = []
for i, t in enumerate(temperatures):
while stack and stack[-1][1] < t:
pop_i, pop_t = stack.pop()
res[pop_i] = i - pop_i
stack.append((i, t))
print(stack)
return res
- for i, t in enumerate(temperatures):
- i -> index
- t -> temperature's element
- stack[-1][1]
- ex) stack = [(0, 73), (1, 74), (2, 75)]
- stack[1] → (1, 74)
- stack[1][-1] → 74 (the last item of the tuple)
- ex) stack = [(0, 73), (1, 74), (2, 75)]
'IT > Computer Science' 카테고리의 다른 글
[Neetcode/Linked Lists] Linked List Cycle Detection (0) | 2025.07.02 |
---|---|
[Neetcode/Array, Hash Table] Group Anagrams (0) | 2025.07.01 |
[Neetcode/Stack] Minimum Stack (0) | 2025.06.28 |
[Leetcode/DFS, Graph] 1971. Find if Path Exists in Graph (0) | 2025.06.25 |
[Neetcode/String Preprocessing ] Valid Palindrome (0) | 2025.06.24 |