我试图从Lua中的表中减去表,因此返回表将是从t2减去t1. 这似乎有效,但有更有效的方法吗? function array_sub(t1, t2)-- Substract Arrays from Array -- Usage: nretable = array_sub(T1, T2) -- removes T1 from T2 ta
这似乎有效,但有更有效的方法吗?
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)加速.