[Leetcode] 23. Merge k Sorted Lists

Problem:

Merge k sorted linked lists and return it as one sorted list. Analyze
and describe its complexity.

Idea:

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值