LeetCode Everyday:坚持价值投资,做时间的朋友!!!
题目:
合并k
个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
- 示例 1:
输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6
代码
方法一: 优先级队列 题解
执行用时:88 ms, 在所有 Python3 提交中击败了75.77%的用户
内存消耗:16.7 MB, 在所有 Python3 提交中击败了7.14%的用户
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
from typing import List
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
import heapq
dummy = ListNode(0)
p = dummy
head = []
for i in range(len(lists)):
if lists[i] :
heapq.heappush(head, (lists[i].val, i))
lists[i] = lists[i].next
while head:
val, idx = heapq.heappop(head)
p.next = ListNode(val)
p = p.next
if lists[idx]:
heapq.heappush(head, (lists[idx].val, idx))
lists[idx] = lists[idx].next
return dummy.next
"""
For Example: input: [
1->4->5,
1->3->4,
2->6
]
output: 1->1->2->3->4->4->5->6
"""
l1 = ListNode(1)
l1.next = ListNode(4)
l1.next.next = ListNode(5)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
l3 = ListNode(2)
l3.next = ListNode(6)
lists = [l1, l2, l3]
solution = Solution()
result = solution.mergeKLists(lists)
print('输出为:%d->%d->%d->%d->%d->%d->%d->%d' % \
(result.val, result.next.val, result.next.next.val, result.next.next.next.val,\
result.next.next.next.next.val, result.next.next.next.next.next.val,\
result.next.next.next.next.next.next.val, result.next.next.next.next.next.next.next.val))
方法二: 分治 题解
执行用时:120 ms, 在所有 Python3 提交中击败了37.66%的用户
内存消耗:23.7 MB, 在所有 Python3 提交中击败了7.14%的用户
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
from typing import List
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:return
n = len(lists)
return self.merge(lists, 0, n-1)
def merge(self,lists, left, right):
if left == right:
return lists[left]
mid = left + (right - left) // 2
l1 = self.merge(lists, left, mid)
l2 = self.merge(lists, mid+1, right)
return self.mergeTwoLists(l1, l2)
def mergeTwoLists(self,l1, l2):
if not l1:return l2
if not l2:return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
"""
For Example: input: [
1->4->5,
1->3->4,
2->6
]
output: 1->1->2->3->4->4->5->6
"""
l1 = ListNode(1)
l1.next = ListNode(4)
l1.next.next = ListNode(5)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
l3 = ListNode(2)
l3.next = ListNode(6)
lists = [l1, l2, l3]
solution = Solution()
result = solution.mergeKLists(lists)
print('输出为:%d->%d->%d->%d->%d->%d->%d->%d' % \
(result.val, result.next.val, result.next.next.val, result.next.next.next.val,\
result.next.next.next.next.val, result.next.next.next.next.next.val,\
result.next.next.next.next.next.next.val, result.next.next.next.next.next.next.next.val))
参考
- https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/leetcode-23-he-bing-kge-pai-xu-lian-biao-by-powcai/