容量翻倍,十六次 append 一共搬了多少
从容量 1 开始,满了就翻倍。做 16 次 append,一共搬动了多少个元素?
N = 16
def moves(n, grow):
"""模拟 n 次 append。返回 (一共搬了多少个元素, 单次最多搬几个)"""
cap, size, total, worst = 1, 0, 0, 0
for _ in range(n):
if size == cap:
total += size
worst = max(worst, size)
cap = grow(cap)
size += 1
return total, worst
total, worst = moves(N, lambda c: c * 2)
print(total)
全部评论