题解 | #两个有序数组间相加和的Topk问题#

两个有序数组间相加和的Topk问题

https://www.nowcoder.com/practice/7201cacf73e7495aa5f88b223bbbf6d1

import sys
import heapq as hq
from collections import defaultdict, Counter
dd = defaultdict(list)
cter = Counter()
q = []
n, k = [int(c) for c in input().strip().split(" ")]
arr1 = reversed([int(c) for c in input().strip().split(" ")])
arr1 = [c for c in arr1]
arr2 = reversed([int(c) for c in input().strip().split(" ")])
arr2 = [c for c in arr2]
[hq.heappush(q,(-(arr1[0]+arr2[i]),0,i)) for i in range(len(arr2)) ]
res = []
for i in range(k):
    item = hq.heappop(q)
    res.append(-item[0])
    hq.heappush(q, (-(arr1[item[1]+1]+arr2[item[2]]),item[1]+1,item[2]))
print(" ".join([str(c) for c in res]))

#优先队列的应用#
全部评论

相关推荐

2 2 评论
分享
牛客网
牛客企业服务