【发布时间】:2021-12-27 19:57:02
【问题描述】:
我尝试做的是通过分而治之的方法检查给定数组是否按升序排列。
我想知道附加返回案例 (a⌊n/2⌋−1 ≤ a⌊n/2⌋) 背后的逻辑是什么来达到最终结果。我试图在不查看解决方案的情况下解决问题,但我无法弄清楚作者是如何发现/设计a⌊n/2⌋−1 ≤ a⌊n/2⌋ 案例的。我真的很难发掘这个案子。
实际上,为什么不改用a⌊n/2⌋ ≤ a⌊n/2⌋+1? 而基本情况,为什么当我从基本情况(即h<l)中删除相等性时我会出现堆栈溢出?
通过反复试验的方法,我尝试编写以下内容。
def co(a, l, h):
if h <= l:
return True
mid = l + ((h-l)//2)
cl = co(a, l, mid-1)
rl = co(a, mid+1, h)
return rl and cl and a[mid] < a[mid+1]
# how is a[mid] < a[mid+1] devised ??
# why not a[mid-1] < a[mid] ??
#c = [3, 5, 7, 9, 11,12]
c = [3, 5]
print(co(c, 0, len(c) - 1))
【问题讨论】:
-
n是数组的长度(或当前问题的大小)。对于最小的相关案例n = 2,索引n//2 + 1将超出范围,但n//2 - 1不会。 -
你写:“我试着写以下”,但是在那个代码中你写“a[mid] ....那么,你是不是写了代码,然后问我们你写了什么?
标签: algorithm recursion math divide-and-conquer off-by-one