【发布时间】:2020-02-20 01:52:53
【问题描述】:
没能google到这个问题的名字,希望这个问题对社区有所贡献。
假设我们有两个排序的数字数组,例如:
2 8
12 18
45 35
85 48
87 49
97 59
我们希望首先从两个数组中有效地获取k (10) 个最小的数字总和组合。在我们的例子中是:
2 + 8 = 10
2 + 18 = 20
12 + 8 = 20
12 + 18 = 30
2 + 35 = 37
12 + 35 = 47
2 + 48 = 50
2 + 49 = 51
45 + 8 = 53
12 + 48 = 60
什么是正确的方法?我编写了一个幼稚的实现(由@sanyash 改进),但它没有利用数组已排序的事实,并且问题在线性时间内感觉可行......
def smallest_product(k, arr1, arr2):
product_iter = itertools.product(
itertools.islice(arr1, k),
itertools.islice(arr2, k),
)
product_sorted = sorted(product_iter, key=sum)
product_sliced = itertools.islice(product_sorted, k);
return list(product_sliced)
print(smallest_product(10,
[ 2, 12, 45, 85, 87, 98],
[ 8, 18, 35, 48, 49, 59]))
类似问题:efficient sorted Cartesian product of 2 sorted array of integers(但它处理创建一个完整的结果数组,而在我的情况下,我只需要前几个值)
附:我添加了python 标签,因为它是一道数学题,但我很乐意使用任何语言的解决方案,或者只是解释,或者维基百科的链接......
【问题讨论】:
标签: python algorithm sorting iteration cartesian-product