|
| 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