LeetCode Hard: 23. Merge k Sorted Lists
一、题目
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
合并K个有序数组
二、思路
递归或者分治法,先把K个数组分成2组,变成合并两组数组,接着一直分下去,递归到最后,变成合并两个单个数组
三、代码
#coding:utf-8 # Definition for singly-linked list. import heapq class ListNode: def __init__(self, x): self.val = x self.next = None class Solution0: def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ """ heapq使用说明 a为普通列表 - heapq.heapify(a) 调整a,使得其满足最小堆 - heapq.heappop(a) 从最小堆中弹出最小的元素 - heapq.heappush(a,b) 向最小堆中压入新的元素 heap = [] for l in lists: if l != None: heap.append((l.val, l)) heapq.heapify(heap) dummy = ListNode(0) cur = dummy while heap: _, h = heapq.heappop(heap) cur.next = h cur = cur.next if h.next: heapq.heappush(heap, (h.next.val, h.next)) return dummy.next """ if len(lists) == 0: return None if len(lists) == 1: return lists[0] #merge sort each two linked list l1 = self.mergeKLists(lists[:,len(lists)//2]) l2 = self.mergeKLists(lists[len(lists)//2:]) head = self.mergetwoLists(l1,l2) return head def mergetwoLists(self,l1,l2): if l1 is None: return l2 if l2 is None: return l1 p = ListNode(0) dummyhead = p while l1 is not None and l2 is not None: if l1.val < l2.val: p.next = l1 l1 = l1.next p = p.next else: p.next = l2 l2 = l2.next p = p.next if l1 is None: p.next = l2 else: p.next = l1 return dummyhead.next
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢