题目:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
代码:oj测试通过 Runtime: 231 ms
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 # @param a list of ListNode 9 # @return a ListNode 10 def mergeKLists(self, lists): 11 # none 12 if len(lists) == 0: 13 return None 14 # only one list 15 if len(lists) == 1: 16 return lists[0] 17 # merge sort each two linked list 18 l1 = self.mergeKLists(lists[:len(lists)/2]) 19 l2 = self.mergeKLists(lists[len(lists)/2:]) 20 head = self.mergeTwoLists(l1,l2) 21 return head 22 23 # merge two sorted linked list 24 def mergeTwoLists(self, l1, l2): 25 if l1 is None: 26 return l2 27 if l2 is None: 28 return l1 29 p = ListNode(0) 30 dummyhead = p 31 while l1 is not None and l2 is not None: 32 if l1.val < l2.val: 33 p.next = l1 34 l1 = l1.next 35 p = p.next 36 else: 37 p.next = l2 38 l2 = l2.next 39 p = p.next 40 if l1 is None: 41 p.next = l2 42 else: 43 p.next = l1 44 return dummyhead.next
思路:
总体的思路是模仿归并排序。
这里给的参数是多个链表的头结点数组,将头节点数组不断二分;直到只剩下一个头结点,返回该头节点到上一层,并在上一层中将两个有序链表合并。
将两个有序链表merge的代码和思路,在这篇日志中可以看到
http://www.cnblogs.com/xbf9xbf/p/4186905.html
另,网上还有一种用堆的方法,后续再去试探这种方法,并把另一种方法的代码补上。
另,关于该问题的算法复杂度O(nklogk) (n为单个链表的最大长度,k为链表个数),个人觉得下面这篇日志表述的比较好,共享一下