Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 448caf4

Browse files
committedJun 5, 2025·
merge-k-sorted-lists solution (py)
1 parent 63c30bb commit 448caf4

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
 

‎merge-k-sorted-lists/hi-rachel.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
https://leetcode.com/problems/merge-k-sorted-lists/description/
3+
4+
문제: k개의 링크드 리스트가 주어지고, 각 링크드 리스트가 오름차순으로 정렬이 되어있다. 모든 링크드 리스트를 병합하여 하나의 정렬된 링크드 리스트를 만들어라.
5+
6+
풀이:
7+
heapq를 쓰면 항상 가장 작은 값을 O(log k) 시간에 꺼낼 수 있음.
8+
heapq -> 최소 힙 구조 -> 내부적으로 항상 가장 작은 값이 루트에 오도록 정렬됨.
9+
10+
1. 각 리스트의 첫 노드를 heap에 넣음 (val, 고유번호, 노드)
11+
2. heap에서 가장 작은 값 꺼내면서 결과 리스트 구성
12+
3. 다음 노드를 힙에 추가
13+
14+
TC: O(n log k), SC: O(k)
15+
n = 모든 리스트의 노드 수
16+
k = 리스트의 개수
17+
"""
18+
19+
from typing import List, Optional
20+
import heapq
21+
22+
# Definition for singly-linked list.
23+
class ListNode:
24+
def __init__(self, val=0, next=None):
25+
self.val = val
26+
self.next = next
27+
28+
29+
class Solution:
30+
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
31+
heap = []
32+
33+
# 1. 각 리스트의 첫 노드를 heap에 넣음 (val, 고유번호, 노드)
34+
for idx, node in enumerate(lists):
35+
if node:
36+
heapq.heappush(heap, (node.val, idx, node))
37+
38+
dummy = curr = ListNode(-1)
39+
40+
# 2. heap에서 가장 작은 값 꺼내면서 결과 리스트 구성
41+
while heap:
42+
val, idx, node = heapq.heappop(heap) # 가장 작은 노드 꺼내기
43+
curr.next = node # 결과 리스트에 붙이기
44+
curr = curr.next # 다음 노드로 이동
45+
46+
if node.next:
47+
# 다음 노드를 힙에 추가
48+
heapq.heappush(heap, (node.next.val, idx, node.next))
49+
50+
return dummy.next

0 commit comments

Comments
 (0)
Please sign in to comment.