Problem:
Merge k sorted linked lists and return it as one sorted list. Analyze
and describe its complexity.
Idea:
General solution (the same as Merge 2 Sorted Lists Question) Use k index to record every position of k sorted lists individually. Compare values of every ListNodes and record the ListNode with smaller value and then move backward.
Priority Queue. Construct a sorted Priority Queue with first item of every List. Then record and remove the first item of Priority Queue, after with insert next item who is in the same list with the removed item.
Heap solution. A little common with Priority Queue, just record and pop the first item in heap.
Solution :
solution for 2:
class Solution(object):
def insertItem(self,tmpItem,tmplist):
lenlist = len(tmplist)
for i in xrange(lenlist):
if tmplist[i][0].val >= tmpItem[0].val:
tmplist.insert(i,tmpItem)
break
if lenlist == len(tmplist):
tmplist.append(tmpItem)
return tmplist
def mergeKLists(self, lists):
klen = len(lists)
headNode = ListNode(0)
tmpNode = headNode
tmplist = []
for i in xrange(klen):
if lists[i] != None:
tmplist.append((lists[i],i))
tmplist = sorted(tmplist, key=lambda item: item[0].val)
while len(tmplist) != 0:
tmpNode.next = ListNode(tmplist[0][0].val)
tmpNode = tmpNode.next
tmpItem = (tmplist[0][0].next,tmplist[0][1])
tmplist.remove(tmplist[0])
if tmpItem[0] != None:
tmplist = self.insertItem(tmpItem,tmplist)
return headNode.next
(ref)solution for 3:
def mergeKLists(self, lists):
from heapq import heappush, heappop, heapreplace, heapify
dummy = node = ListNode(0)
h = [(n.val, n) for n in lists if n]
heapify(h)
while h:
v, n = h[0]
if n.next is None:
heappop(h) #only change heap size when necessary
else:
heapreplace(h, (n.next.val, n.next))
node.next = n
node = node.next
return dummy.next
Ref: http://blog.csdn.net/magicbean2/article/details/53618115