【发布时间】:2020-09-16 19:14:03
【问题描述】:
如果给定一个输入 [s1, ..., sn],同时也给定一个属性 P,程序应该输出满足这个 P 的连续对。
例如,如果 P 是对中两个元素之和应小于 20,则输入 [1,10,29,17] 应输出 [(1,10)],因为它是唯一满足此 P 的连续对。
为简单起见,假设检查属性 P 是常数时间。一个简单的解决方案是遍历列表,使其为 O(n)。
例如在python中
def f(ls, P: callable):
r = []
for i in range(len(ls)-1):
if P(ls[i], ls[i+1]):
r.append((ls[i], ls[i+1]))
return r
assert f([1,10,29,17], lambda x, y: x+y<=20) == [(1,10)]
assert f([1,10,29,17], lambda x, y: x < y) == [(1,10),(10,29)] # checking if first is smaller than the second
但我想知道是否有一些方法可以加快这个过程。谢谢!
【问题讨论】: