| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- stratascratch
- 생성형AI
- Stack
- 슬라이딩윈도우
- SQL
- array
- 릿코드
- two-pointer
- 리트코드
- nlp
- heap
- dfs
- 니트코드
- tree
- 파이썬알고리즘
- 알고리즘
- sql코테
- Python3
- binary Tree
- BFS
- 투포인터
- 파이썬
- graph
- Python
- Greedy
- GenerativeAI
- 코드업
- GenAI
- LeetCode
- codeup
Archives
- Today
- Total
Tech for good
[Leetcode/Array, Heap (Priority Queue) 1046. Last Stone Weight 본문
IT/Computer Science
[Leetcode/Array, Heap (Priority Queue) 1046. Last Stone Weight
Diana Kang 2025. 8. 19. 08:52
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
# what is heap? => find min/max using push() or pop()
# it allows handling new value effeciently when we even insert new values.
pq = [-x for x in stones]
# pq = [-2, -7, -4, -1, -8, -1]
heapify(pq) # heapify() -> make it into binarry tree for efficiency (only half-through traversal)
while len(pq) > 1:
heaviest = -1 * heappop(pq)
second_heaviest = -1 * heappop(pq)
if heaviest != second_heaviest:
new_weight = (heaviest - second_heaviest)
heappush(pq, -1 * new_weight)
return -1 * pq[0] if len(pq) > 0 else 0


'IT > Computer Science' 카테고리의 다른 글
| [Leetcode/Binary Tree, CBT, PBT] 222. Count Complete Tree Nodes (0) | 2025.11.22 |
|---|---|
| [Leetcode/Array, Heap (Priority Queue)] 973. K Closest Points to Origin (0) | 2025.08.20 |
| [Codepath/BFS, Graph] Count Connected Components (0) | 2025.08.12 |
| [Codepath/BFS, Graph] Find Path (0) | 2025.08.12 |
| [Leetcode/DFS, BFS, Graph, Matrix] 200. Number of Islands (0) | 2025.08.09 |