给定 k 个大小为 n 的排序数组,合并它们并打印排序后的输出。
我遵循的算法是
- 遍历每个数组
- 选择 k 个数组中的第 i 个索引
insert()
在最小堆中delMin()
并附加结果数组。
from heapq import heappop, heappush
def merge_k_arrays(list_of_lists):
result = [] #len(list_of_lists[0])*len(list_of_lists)
minHeap= []
n, k=0,0
print(list_of_lists)
while n < len(list_of_lists[0]):
if n ==0:# initial k size heap ready
while k < len(list_of_lists):
element= list_of_lists[k][n]
heappush(minHeap ,element )
k+=1
result.append(heappop(minHeap))
else: # one at a time.
k =0
while k < len(list_of_lists):
element = list_of_lists[k][n]
heappush(minHeap , element)
result.append(heappop(minHeap))
k+=1
n += 1
# add the left overs in the heap
while minHeap:
result.append(heappop(minHeap))
return result
输入:
input = [ [1, 3, 5, 7],
[2, 4, 6, 8],
[0, 9, 10, 11],
]
输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
输入:
input = [ [1, 3, 5, 7],
[2, 4, 6, 8],
[3, 3, 3, 3],
[7, 7, 7,7]
]
输出:
[0, 1, 2, 3, 3, 3, 4, 5, 6, 3, 7, 7, 7, 7, 3, 7, 8, 9, 10, 11]
任何人都可以帮我知道我的算法中缺少什么,以便合并第二个输入中的重复数组吗?