LeetCode----Merge k Sorted Lists
来源:互联网 发布:早岁那知世事艰 编辑:程序博客网 时间:2024/06/18 15:33
Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
分析1:
利用上一道题(合并两个有序链表)代码,进行两两合并,最后得到一个链表。代码如下,然而一直超时。
超时的代码:
def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if len(lists) == 0: return None else: l3 = None for l in lists: l3 = reduce(self.mergetTwoLists, lists) return l3.next
分析2:
利用最小堆的特性,将每个链表放入最小堆中,每次从堆中取出一个ListNode p,同时往里面插入p的后序ListNode(如果存在的话)。我按算法导论的堆的伪码,用Python实现了一个最小堆完成了这道题。如果你看下面这段代码的话,你可以使用Python的heapq模块中的函数替换我写的渣渣代码,同时可以去看看heapq中的实现。
代码:
def Parent(i): return i/2def Left(i): return 2*idef Right(i): return 2*i + 1def minHeapify(h, i): l = Left(i) r = Right(i) if l < len(h) and h[l] < h[i]: minlst = l else: minlst = i if r < len(h) and h[r] < h[minlst]: minlst = r if minlst != i: h[i], h[minlst] = h[minlst], h[i] minHeapify(h, minlst)def buildMinHeap(h): half_len = len(h) / 2 while half_len >= 0: minHeapify(h, half_len) half_len -= 1 return hdef upAdjust(h, i): while i >= 0 and h[Parent(i)] > h[i]: h[Parent(i)], h[i] = h[i], h[Parent(i)] i = Parent(i)def heapPush(h, item): h.append(item) upAdjust(h, len(h) - 1)def heapPop(h): if len(h) == 0: return None min_val = h[0] h[0] = h[len(h) - 1] del h[len(h) - 1] minHeapify(h, 0) return min_val# Definition for singly-linked list.class ListNode(object): def __init__(self, x): self.val = x self.next = Noneclass Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ # from heapq import heappush, heappop, heapify h = [(l.val, l) for l in lists if l] buildMinHeap(h) head = rl = ListNode(0) while h: rl.next = heapPop(h)[1] print rl.next.val rl = rl.next if rl.next: heapPush(h, (rl.next.val, rl.next)) return head.next
0 0
- LeetCode: Merge k Sorted Lists
- LeetCode Merge k Sorted Lists
- LeetCode: Merge k Sorted Lists
- [Leetcode] Merge k Sorted Lists
- [Leetcode] Merge k Sorted Lists
- [Leetcode] Merge K sorted lists
- [LeetCode]Merge k Sorted Lists
- [LeetCode] Merge k Sorted Lists
- LeetCode-Merge k Sorted Lists
- LeetCode: Merge k Sorted Lists
- LeetCode - Merge k Sorted Lists
- LeetCode | Merge k Sorted Lists
- 【leetcode】Merge k Sorted Lists
- Leetcode: Merge k Sorted Lists
- <Leetcode>Merge k Sorted Lists
- [LeetCode] Merge K sorted lists
- [LeetCode] Merge k Sorted Lists
- 【Leetcode】Merge k Sorted Lists
- 指针函数与函数指针的区别
- Android异步更新UI的四种方式
- Lua切割中文字符串,按指定字符,切割字符串
- uva 11090 - Going in Cycle!!(二分+BellmanFord)
- https://readthedocs.org/
- LeetCode----Merge k Sorted Lists
- 迟到问题,其实不扣钱的话就不是问题……
- android屏幕适配
- 测试基础
- Uva-1220 Party at Hali-Bula
- uva 11294 - Wedding(2 sat)
- java基础—7.多线程
- 制作easyui部门选择插件
- 构造,析构与初始化列表