gpt4 book ai didi

lua - 从 Lua 中的表中减去表

转载 作者:行者123 更新时间:2023-12-04 20:17:29 25 4
gpt4 key购买 nike

我正在尝试从 Lua 中的表中减去表,因此返回表将是从 t2 中减去 t1。

这似乎有效,但有没有更有效的方法呢?

 function array_sub(t1, t2)

-- Substract Arrays from Array
-- Usage: nretable = array_sub(T1, T2) -- removes T1 from T2

table.sort( t1 )

for i = 1, #t2 do
if (t2[i] ~= nil) then
for j = 1, #t1 do
if (t2[i] == t1 [j]) then
table.remove (t2, i)
end
end
end
end
return t2
end


local remove ={1,2,3}
local full = {}; for i = 1, 10 do full[i] = i end

local test ={}

local test = array_sub(remove, full)

for i = 1, #test do
print (test[i])
end

最佳答案

是的,有:制作一个包含表t1的所有值的查找表,然后从最后开始遍历表t2。

function array_sub(t1, t2)
local t = {}
for i = 1, #t1 do
t[t1[i]] = true;
end
for i = #t2, 1, -1 do
if t[t2[i]] then
table.remove(t2, i);
end
end
end

已交易 O(#t1)来自 O(#t1*#t2) 的加速空间至 O(#t1+#t2) .

关于lua - 从 Lua 中的表中减去表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23063722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com