提问人:Charlim 提问时间:4/8/2021 最后编辑:Lauren YimCharlim 更新时间:5/10/2021 访问量:107
是否可以在保留 O(1) 访问时间的同时将数组建模为函数?
Is it possible to model arrays as functions while preserving O(1) access times?
问:
将链接列表建模为函数非常容易,无需任何底层集合数据类型,如下所示:
-- This is Lua code, but the specific language shouldn't matter
function createList(first, rest)
return function(isFirst)
if isFirst
then
return first
else
return rest
end
end
end
function nth(list, n)
-- replace with n==0 for 0 indexing,
if (n == 1)
then
return list(true)
else
return nth(list(false), n-1)
end
end
但是,与索引访问具有时间复杂性的数组相比,这具有缺点。我一直在想数组文字很容易实现,这样:O(n)
-- {1, 2, 4, 8} ==
function someArray(n)
if (n == 1)
return 1
elseif (n == 2)
return 2
elseif (n == 3)
return 4
elseif (n == 4)
return 8
end
end
但是我意识到一次浏览每一个仍然是 访问时间 .我考虑了一个 switch 语句,因为我的印象是 C 的 switch 语句直接跳转到与条件结果匹配的标签,但这似乎不正确。对于分支,C 的开关似乎会及时选择一个分支。是否可以在不使用数组的情况下在恒定时间内选择分支?是否有其他技术可以恒定时间访问建模为我错过的函数的数组?elseif
O(n)
n
O(n)
答: 暂无答案
评论