| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- 리트코드
- stratascratch
- array
- 투포인터
- 릿코드
- GenerativeAI
- 알고리즘
- Python3
- nlp
- SQL
- 슬라이딩윈도우
- GenAI
- Greedy
- 니트코드
- 파이썬
- Python
- two-pointer
- dfs
- binary Tree
- 코드업
- codeup
- 생성형AI
- LeetCode
- BFS
- graph
- heap
- tree
- Stack
- 파이썬알고리즘
- sql코테
Archives
- Today
- Total
Tech for good
[Leetcode/Stack] 496. Next Greater Element I 본문


class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
# Dictionary to store the next greater element for each number in nums2
next_greater = {}
stack = []
# Traverse nums2 in order
for num in nums2:
# Maintain a decreasing stack; pop elements smaller than current num
while stack and num > stack[-1]:
smaller = stack.pop()
next_greater[smaller] = num
stack.append(num)
# Remaining elements in stack have no greater element
for num in stack:
next_greater[num] = -1
# Build result for nums1 using the precomputed dictionary
🔍 How it works:
- Stack keeps track of numbers for which we haven't found a next greater element yet.
- As we iterate through nums2, we pop(뺀다) elements from the stack when the current number is greater than the top of the stack — meaning the current number is the next greater element for that top.
- We map each popped number to its next greater number.
- For the result, we just look up each number in nums1 using the dictionary.
🌷 Stack
- push(): 데이터를 넣는다.
- pop(): 데이터를 꺼낸다.
'IT > Computer Science' 카테고리의 다른 글
| [Leetcode/Stack] 682. Baseball Game (0) | 2025.04.16 |
|---|---|
| [Leetcode/Stack] 234. Palindrome Linked List (0) | 2025.04.14 |
| [Leetcode/Heap] 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit (0) | 2025.04.11 |
| [Neetcode/Heap] Last Stone Weight (0) | 2025.04.11 |
| [Neetcode/Heap] Kth Largest Element in a Stream (0) | 2025.04.11 |