|
| 1 | +# Definition for singly-linked list. |
| 2 | +# class ListNode: |
| 3 | +# def __init__(self, val=0, next=None): |
| 4 | +# self.val = val |
| 5 | +# self.next = next |
| 6 | +import heapq |
| 7 | +class Solution: |
| 8 | + """ |
| 9 | + 브루트포스 |
| 10 | + """ |
| 11 | + # def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: |
| 12 | + # dummy = curr = ListNode() |
| 13 | + # while any(lists): |
| 14 | + # val, idx = min((li.val, idx) for idx, li in enumerate(lists) if li) |
| 15 | + # curr.next = ListNode(val) |
| 16 | + # curr = curr.next |
| 17 | + # lists[idx] = lists[idx].next |
| 18 | + # return dummy.next |
| 19 | + |
| 20 | + """ |
| 21 | + 최소힙 활용 |
| 22 | + """ |
| 23 | + # def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: |
| 24 | + # heap = [(li.val, idx) for idx, li in enumerate(lists) if li] |
| 25 | + # heapq.heapify(heap) |
| 26 | + |
| 27 | + # dummy = curr = ListNode() |
| 28 | + # while heap: |
| 29 | + # val, idx = heapq.heappop(heap) |
| 30 | + # curr.next = ListNode(val) |
| 31 | + # curr = curr.next |
| 32 | + |
| 33 | + # lists[idx] = lists[idx].next |
| 34 | + # if lists[idx]: |
| 35 | + # heapq.heappush(heap, (lists[idx].val, idx)) |
| 36 | + # return dummy.next |
| 37 | + |
| 38 | + """ |
| 39 | + 분할정복과 재귀 활용 |
| 40 | + """ |
| 41 | + def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: |
| 42 | + def mergeTwoLists(li1, li2): |
| 43 | + dummy = node = ListNode(-1) |
| 44 | + while li1 and li2: |
| 45 | + if li1.val < li2.val: |
| 46 | + node.next = li1 |
| 47 | + li1 = li1.next |
| 48 | + else: |
| 49 | + node.next = li2 |
| 50 | + li2 = li2.next |
| 51 | + node = node.next |
| 52 | + node.next = li1 if li1 else li2 |
| 53 | + return dummy.next |
| 54 | + |
| 55 | + if len(lists) == 0: |
| 56 | + return None |
| 57 | + |
| 58 | + def dfs(low, high): |
| 59 | + if low == high: |
| 60 | + return lists[low] |
| 61 | + if low + 1 == high: |
| 62 | + return mergeTwoLists(lists[low], lists[high]) |
| 63 | + |
| 64 | + mid = (low + high) // 2 |
| 65 | + li1 = dfs(low, mid) |
| 66 | + li2 = dfs(mid + 1, high) |
| 67 | + return mergeTwoLists(li1, li2) |
| 68 | + |
| 69 | + return dfs(0, len(lists) - 1) |
0 commit comments