腾讯22-合并K个排序链表 leetcode23
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
两种解法,记住,归并的O(nlogk)
和最小堆(插入链表到堆,标准是链表的第一个元素,然后pop出一个链表,这个链表的head第一个元素一定是当前可输出的最小元素,然后把这个链表的第一个元素去掉重新加入到最小堆中,(去掉的意思在链表中无非就是指针后移而已),并不断操作)
代码还是挺难写对的
hard级别的
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from queue import PriorityQueue
#class Solution:
# #方法 2:逐一比较, 小规模可以,但是大规模超时了,应该哪里需要优化一下
# def mergeKLists(self, lists: List[ListNode]) -> ListNode:
# res_node=ListNode(-1)
# cur_node=res_node
# #res_node=pre_node
# while lists!=[None]*len(lists):
# min_index=0
# min_node=lists[0]
# for i in range(0,len(lists)) :
# list=lists[i]
# if list is None:
# continue
# if min_node is None or list.val<min_node.val:
# min_node=list
# min_index=i
# lists[min_index]=lists[min_index].next
# if min_node is not None:
# cur_node.next=min_node
# cur_node=cur_node.next
# cur_node.next=None
# return res_node.next
# class Solution:
# #方法 3:逐一比较, 但比较换成了用优先级队列,即堆的的方式
# def mergeKLists(self, lists: List[ListNode]) -> ListNode:
# head=point=ListNode(0)
# q=PriorityQueue()
# for l in lists:
# if l:
# q.put((l.val,l))
# while not q.empty():
# val,node=q.get()
# point.next=ListNode(val)
# point =point.next
# node= node.next
# if node:
# q.put((node.val,node))
# return head.next
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
amount = len(lists)
interval = 1
while interval < amount:
for i in range(0, amount - interval, interval * 2):
lists[i] = self.merge2Lists(lists[i], lists[i + interval])
interval *= 2
return lists[0] if amount > 0 else lists
def merge2Lists(self, l1, l2):
head = point = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
point.next = l1
l1 = l1.next
else:
point.next = l2
l2=l2.next
#l2 = l1
#l1 = point.next.next
point = point.next
if not l1:
point.next=l2
else:
point.next=l1
return head.next