题解 | #两个有序数组间相加和的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]))

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

相关推荐

10-11 17:45
门头沟学院 Java
走吗:别怕 我以前也是这么认为 虽然一面就挂 但是颇有收获!
点赞 评论 收藏
分享
11-08 13:58
门头沟学院 Java
程序员小白条:竟然是蓝桥杯人才doge,还要花钱申领的offer,这么好的公司哪里去找
点赞 评论 收藏
分享
2 2 评论
分享
牛客网
牛客企业服务