Skip to content

Commit 028dd0f

Browse files
committed
solve(w10): 23. Merge k Sorted Lists
1 parent 1b2a8a9 commit 028dd0f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# https://leetcode.com/problems/merge-k-sorted-lists/
2+
3+
from typing import List, Optional
4+
5+
6+
# Definition for singly-linked list.
7+
class ListNode:
8+
def __init__(self, val=0, next=None):
9+
self.val = val
10+
self.next = next
11+
12+
class Solution:
13+
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
14+
"""
15+
[Complexity]
16+
- TC: O(mlogn) (n = len(lists), m = node์˜ ์ „์ฒด ๊ฐœ์ˆ˜)
17+
- SC: O(n) (min heap)
18+
19+
[Approach]
20+
๊ฐ๊ฐ ์ด๋ฏธ sorted์ธ linked list๋“ค์„ ํ•˜๋‚˜์˜ sorted linked list๋กœ merge ํ•˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ,
21+
์ฃผ์–ด์ง„ ๊ฐ๊ฐ์˜ linked list์—์„œ node ํ•˜๋‚˜์”ฉ์„ ๊บผ๋‚ด์–ด ๋ณด๋ฉฐ ๊ทธ ๊ฐ’์„ ๋น„๊ตํ•˜๋ฉด ๋œ๋‹ค.
22+
์ด๋•Œ, ๊ธธ์ด๊ฐ€ n(= len(lists))์ธ min heap์„ ์‚ฌ์šฉํ•˜๋ฉด ๊ฐ linked list์—์„œ์˜ node ํ•˜๋‚˜์”ฉ์„ ๋‹ด์•„ ์ตœ์†Ÿ๊ฐ’์„ ๊ฐ€์ง„ node๋ฅผ O(logn)์— pop ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.
23+
๋‹ค๋งŒ, min heap์— node๋งŒ ๋„ฃ์œผ๋ฉด ๋น„๊ตํ•  ์ˆ˜ ์—†์œผ๋ฏ€๋กœ, ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ตฌ์„ฑ๋œ tuple์„ min heap์— ๋„ฃ๋Š”๋‹ค.
24+
(* ํŒŒ์ด์ฌ์—์„œ tuple ๋ผ๋ฆฌ ๋น„๊ตํ•  ๋•Œ๋Š” ์•ž ์›์†Œ๋ถ€ํ„ฐ ์ฐจ๋ก€๋กœ ๋น„๊ต๋˜๋ฉฐ, ์•ž ์›์†Œ์—์„œ ๊ฐ’์ด ๋™์ผํ•˜๋ฉด ๋‹ค์Œ ์›์†Œ๋กœ ๋„˜์–ด๊ฐ„๋‹ค.)
25+
(value, index in lists, node)
26+
- value: ๊ฐ€์žฅ ๋จผ์ € value๋ฅผ ๋น„๊ตํ•˜๋„๋ก ํ•œ๋‹ค.
27+
- index in lists: ๋งŒ์•ฝ value๊ฐ€ ์„œ๋กœ ๊ฐ™์€ ์ƒํ™ฉ์ด๋ผ๋ฉด ๋”์ด์ƒ ์ตœ์†Ÿ๊ฐ’์„ ๊ณ ๋ฅด๊ธฐ ์œ„ํ•œ ๋น„๊ต๊ฐ€ ์ง„ํ–‰๋˜์ง€ ์•Š๋„๋ก uniqueํ•œ ๊ฐ’์ธ lists์—์„œ์˜ index๋กœ ๋น„๊ตํ•˜๋„๋ก ํ•œ๋‹ค.
28+
์‹ค์ œ๋กœ ์‚ฌ์šฉ๋˜๋Š” ๊ฐ’์€ ์•„๋‹ˆ๋‚˜, node ๋ผ๋ฆฌ ๋น„๊ต๊ฐ€ ๋ถˆ๊ฐ€๋Šฅํ•˜๋ฏ€๋กœ ์‚ฌ์šฉํ•œ๋‹ค.
29+
- node: ๊ฒฐ๊ณผ merged linked-list์— ๋„ฃ๊ธฐ ์œ„ํ•ด ์‹ค๋ฌผ node๊ฐ€ ํ•„์š”ํ•˜๋ฉฐ, next node๋ฅผ min heap์— ๋„ฃ์„ ๋•Œ ํ•„์š”ํ•˜๋‹ค.
30+
"""
31+
import heapq
32+
33+
# ์ฃผ์–ด์ง„ ๊ฐ linked list์˜ ์ฒซ node๋ฅผ min heap์— ๋„ฃ๊ธฐ
34+
q = [(node.val, i, node) for i, node in enumerate(lists) if node]
35+
heapq.heapify(q) # list๋ฅผ ๋จผ์ € ์™„์„ฑํ•˜๊ณ  heapifyํ•˜๋ฉด O(n)
36+
37+
res = curr = ListNode()
38+
39+
while q:
40+
# ์ตœ์†Ÿ๊ฐ’์„ ๊ฐ€์ง„ node ์ถ”์ถœ
41+
value, i, node = heapq.heappop(q)
42+
43+
# res์— node ์ถ”๊ฐ€
44+
curr.next = node
45+
curr = curr.next
46+
47+
# node์˜ ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ min heap์— ๋„ฃ์–ด์ฃผ๊ธฐ
48+
if node.next:
49+
heapq.heappush(q, (node.next.val, i, node.next))
50+
51+
return res.next

0 commit comments

Comments
ย (0)