我试图从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
Run Code Online (Sandbox Code Playgroud)
是的,有:制作一个包含表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
Run Code Online (Sandbox Code Playgroud)
O(#t1)从O(#t1*#t2)到的加速交易空间O(#t1+#t2)。