数组与矩阵---打印N个数组整体最大的TopK

来源:互联网 发布:网络交接不可用 编辑:程序博客网 时间:2024/06/05 09:38

【题目】

  有N个长度不一的数组,所有的数组都是有序的,请从大到小打印这个N个数组整体最大的前K个数。
  例如,输入含有N行元素的二维数组可以代表N个一维数组。
  219, 405, 538, 845, 971
  148, 558
  52, 99, 348, 691
  再输入整数k = 5,则打印:
  971, 845, 691, 558, 538

【要求】

  1. 如果所有数组的元素个数小于K,则从大到小打印所有的数
  2. 要求时间复杂度为O(KlogN)

【基本思路】

  本题的解法是利用堆结构和堆排序的过程完成的,具体过程如下:

  1. 构建一个大小为N的大根堆,建堆的过程就是把每一个数组的最后一个值,也就是该数组的最大值,依次加入到堆里,这个过程就是建堆的调整过程。

  2. 建好堆以后,此时堆顶的元素就是所有数组中最大的元素,打印堆顶元素。

  3. 假设堆顶的元素来自 a 数组的 i 位置,那么将堆顶的元素用a[i-1]替换,然后从堆的头部重新调整堆。如果发现此时 a 数组已经没有元素,那么就将堆顶元素与堆尾元素交换,同时令堆的大小减1,仍然是从堆的头部重新调整堆。

  4. 每次都可得到一个堆顶元素,打印k个堆顶元素,就是最终的结果。

为了知道每一次的堆顶元素来自哪一个数组的哪一个位置,我们可以定义如下的heap类:

class HeapNode:    def __init__(self, value, arrNum, index):        self.value = value        self.arrNum = arrNum        self.index = index

【代码实现】

def printTopK(matrix, k):    def heapInsert(heap, i):        if i == 0:            return        parent = (i-1) // 2        tmp = heap[i]        while tmp.value > heap[parent].value:            heap[i] = heap[parent]            i = parent            parent = (i-1) // 2        heap[i] = tmp    def heapify(heap, i, n):        child = 2 * i + 1        tmp = heap[i]        while child < n:            if child < n-1 and heap[child].value < heap[child+1].value:                child += 1            if heap[child].value > tmp.value:                heap[i] = heap[child]                i = child                child = 2 * i + 1            else:                break        heap[i] = tmp    if matrix == None or len(matrix) == 0:        return []    heapSize = len(matrix)    heap = [0 for i in range(heapSize)]    for i in range(len(heap)):        index = len(matrix[i]) - 1        heap[i] = HeapNode(matrix[i][index], i, index)        heapInsert(heap,i)    for i in range(k):        if heapSize == 0:            break        print(heap[0].value, end=' ')        if heap[0].index != 0:            heap[0].value = matrix[heap[0].arrNum][heap[0].index-1]            heap[0].index -= 1        else:            heap[0] = heap[-1]            heapSize -= 1        heapify(heap, 0, heapSize)
原创粉丝点击